0
0
DockerConceptBeginner · 3 min read

What is USER in Dockerfile: Explanation and Usage

The 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.

dockerfile
FROM ubuntu:22.04
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
USER appuser
CMD ["whoami"]
Output
appuser
🎯

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.

Key Takeaways

The USER instruction sets which user runs commands and the container process.
Running containers as non-root users improves security.
Always create or ensure the user exists before using USER.
Use USER in production to follow best security practices.
Default user is root if USER is not specified.