What is USER in Dockerfile: Explanation and Usage
USER instruction in a Dockerfile sets the username or UID that the container will run as. It changes the default user from root to a specified user, improving security and control over container processes.How It Works
The USER instruction in a Dockerfile tells Docker which user should run the commands inside the container. By default, containers run as the root user, which has full control but can be risky for security. Using USER is like telling a restaurant kitchen to let a specific chef handle the cooking instead of the head chef who has all access.
This instruction changes the user context for all following commands in the Dockerfile and when the container runs. It can use a username or a numeric user ID (UID). If the user does not exist in the container, Docker will throw an error, so the user must be created first or be part of the base image.
Example
This example shows how to create a user and switch to it using USER in a Dockerfile.
FROM ubuntu:22.04 RUN groupadd -r appgroup && useradd -r -g appgroup appuser USER appuser CMD ["whoami"]
When to Use
Use USER to improve container security by avoiding running as root. This is important when running applications that do not need full system access, reducing risks if the container is compromised.
It's common in production environments, especially for web servers, databases, or any service where least privilege is a best practice. Also, some platforms require non-root users for compliance or security policies.
Key Points
- USER sets the user for running commands and the container process.
- Default user is root unless changed.
- User must exist in the container image.
- Improves security by limiting permissions.
- Common in production and security-focused setups.