Dockerfile by Example: User Permission Configuration
Running containers as root is a security risk. This sample code shows how to create a dedicated user and switch context to enforce least privilege.
Code
FROM ubuntu:22.04
# 1. Create a group and user
# -r: system account
# -g: add to group
RUN groupadd -r myapp && useradd -r -g myapp myapp
# 2. Set ownership of necessary directories
WORKDIR /app
RUN chown -R myapp:myapp /app
# 3. Switch to the non-root user
USER myapp
# 4. Subsequent commands run as 'myapp'
# This prevents the container from modifying system files
CMD ["./start-app.sh"]Explanation
By default, Docker containers run as the root user, which poses a significant security risk. If an attacker manages to break out of the container (container escape), they could potentially gain root access to the host system. To mitigate this, it is a critical best practice to create a non-privileged user within the Dockerfile and switch to that user using the USER instruction before running the application.
Security benefits of non-root users:
- Limits the blast radius of potential security vulnerabilities
- Prevents accidental modification of system files inside the container
- Complies with "Least Privilege" security principles
- Required by many secure container orchestration environments (e.g., OpenShift)
When switching users, you must ensure that the new user has the necessary permissions to read and write to the application's working directory. This is typically handled by creating the user and group explicitly (using groupadd and useradd) and then using chown to transfer ownership of the application files. Note that ports below 1024 are privileged and cannot be bound by non-root users unless specific capabilities are granted.
Code Breakdown
groupadd ... && useradd ... creates a system user/group pair.chown -R ... ensures the new user owns the app directory.USER myapp switches the active user for all following commands.CMD executes with the restricted permissions of 'myapp'.
