CodeBlanks Logo Icon CodeBlanks

Switching users

Learn to switch the container user with -u.

Changing the user

Processes in a container run as root by default. If a vulnerability is found, the attacker gains root privileges inside the container. That is why an unprivileged user is created in the Dockerfile and switched to with USER:

FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node . .
USER node
CMD ["node", "server.js"]

Official Node images include a ready node user.

Creating a user and -u

In images without a ready user, the user is created with RUN. At run time, the user can be changed with -u user or -u UID:GID:

FROM python:3.12-slim
RUN useradd --create-home --uid 1000 app
USER app

$ docker run --rm -u 1000:1000 alpine id
uid=1000 gid=1000 groups=1000

Listening on ports below 1024 requires root; with an unprivileged user you make the application listen on a high port like 8080.

Practice Python with an unprivileged user

Write a Dockerfile based on python:3.12-slim: create a user with useradd --create-home --uid 1000 app; WORKDIR /app; copy the files with --chown=app:app (COPY --chown=app:app . .); USER app; CMD is python app.py in exec form.

Starter code

terminal
# buraya yaz

Sample solution

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

Expected output

[+] Building 3.8s (9/9) FINISHED
 => naming to docker.io/library/api:latest done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main reason to run a non-root user in a container?

  • To be able to open ports
  • To reduce the damage in case of a vulnerability Correct answer
  • To speed up the application
  • To shrink the image

Explanation: The principle of least privilege applies to containers too.

2 Run the following instructions as the app user.

Question
____ app
Answer
USER app

Explanation: USER sets the user for the following RUN, CMD and ENTRYPOINT.

3 Match.

Term Meaning
USER User in the Dockerfile
-u 1000:1000 UID:GID at run time
useradd Creates a user
port 8080 Needs no root

All lessons in Beginner