How to Use Non-Root User in Docker Containers
To use a
non-root user in Docker, create a user inside the Dockerfile with RUN adduser or useradd, then switch to that user using USER username. This prevents running containers as root, improving security.Syntax
In a Dockerfile, you create a new user and switch to it using these commands:
RUN adduser --disabled-password username- creates a new user without a password.USER username- switches the container to run as this user.
This ensures commands run inside the container do not have root privileges.
dockerfile
FROM alpine:latest
RUN adduser -D myuser
USER myuser
CMD ["sh"]Example
This example Dockerfile creates a non-root user named appuser and runs a simple command as that user.
dockerfile
FROM ubuntu:22.04 # Create a non-root user named appuser RUN useradd -m appuser # Switch to the new user USER appuser # Run a command to show current user CMD ["whoami"]
Output
appuser
Common Pitfalls
Common mistakes when using non-root users in Docker include:
- Not creating the user before switching with
USER, causing build errors. - Forgetting to set proper permissions on files or directories the user needs to access.
- Running commands as root before switching user but leaving files owned by root, causing permission issues.
Always create the user first, set correct permissions, then switch user.
dockerfile
FROM alpine:latest # Wrong: switching user before creating it USER appuser RUN adduser -D appuser # Right: # RUN adduser -D appuser # USER appuser
Quick Reference
Tips for using non-root users in Docker:
- Create the user with
adduseroruseradd. - Set file permissions so the user can access needed files.
- Switch to the user with
USER usernamebefore running commands. - Test the container runs as the non-root user using
whoamiorid.
Key Takeaways
Always create a non-root user in your Dockerfile before switching to it.
Use the USER instruction to run container processes as the non-root user.
Set proper file and directory permissions for the non-root user.
Running containers as non-root improves security and reduces risks.
Test your container user with commands like whoami to confirm.