A secure image

A non-root user, a fresh base and nothing extra.

By default the process in a container runs as root. Container isolation restricts this user, but if a vulnerability is found in the application, the attacker gets root rights inside the container, which makes the next step easier. That is why an ordinary user is created in the image and the USER instruction switches to it.

FROM python:3.12-slim
RUN useradd --create-home --uid 10001 app
WORKDIR /home/app
COPY --chown=app:app . .
USER app
CMD ["python", "main.py"]

Everything after USER app runs as an ordinary user, and the service itself starts without root rights. --chown makes the application's files available to this user right away.

The fewer programs an image contains, the fewer vulnerabilities it has and the fewer tools an attacker could use. The slim and alpine variants contain only the core of the system. The base image is updated regularly: vulnerabilities get fixed in it, and rebuilding with the same tag pulls in the fixes. You can check an image for known vulnerabilities with a scanner, for example the docker scout cves command.

A few more rules. Do not run containers with --privileged unless you understand why: the flag removes almost all restrictions. Add only the files you need to the image, using .dockerignore. Pin the base image versions so the build is repeatable, and update them deliberately rather than by accident through latest.

A common mistake is to switch to USER app at the start of the Dockerfile and then wonder why RUN apt-get install fails with a permission error. Packages are installed before USER, as root, and the switch to the ordinary user happens at the end, before CMD. Another mistake is a port below 1024: it is harder for an ordinary user to listen on it, so the application in the container listens on, say, 8080, and it is published outside on whatever port you need.

Practice

  1. Why USER

    Why switch to an ordinary user with the USER instruction in a Dockerfile?

    • To make the image build faster
    • So that an attacker does not get root rights through a vulnerability
    • Without USER the container will not start
    • To make the layer cache work
  2. Good practices

    What makes an image more secure? Mark all.

    • Running as an ordinary user
    • A minimal base image (slim, alpine)
    • Running with --privileged
    • Rebuilding regularly with an updated base image
  3. The user instruction

    Which Dockerfile instruction switches to an ordinary user? Write its name.