Course contentsShow
← Cloud and Infrastructure
Lesson 1011 of 2,98920. Docker in DepthFree lesson

USER: Running as Non-Root

Master USER instruction for switching execution context, creating users, and security best practices.

USER: Running as Non-Root

What you'll learn: How to use the USER instruction in Dockerfiles to run containers as non-root users for better security.

Why Non-Root Matters

By default, processes inside a container run as the root user (UID 0), which has full administrative privileges. If an attacker compromises your containerized application, they inherit those root privileges within the container. Running as a non-root user dramatically limits the damage an attacker can do—it's like giving a guest limited access instead of your master keys.

The USER Instruction

The USER instruction switches the execution context for all subsequent RUN, CMD, and ENTRYPOINT commands. Once you set a user, all following operations run with that user's permissions.

Basic syntax:

USER <username_or_uid>

Creating and Switching Users

Since most base images don't include custom users, you typically create one first using RUN:

FROM ubuntu:22.04

# Create a non-root user
RUN useradd -m -u 1000 appuser

# Switch to that user
USER appuser

# All commands from here run as 'appuser'
WORKDIR /home/appuser
COPY --chown=appuser:appuser app.py .
CMD ["python3", "app.py"]

Security Best Practices

  • Always switch to non-root before the final CMD or ENTRYPOINT
  • Use numeric UIDs (like USER 1000) for better compatibility across systems
  • Set file ownership with --chown in COPY instructions so your user can access files
  • Never run production workloads as root unless absolutely necessary

Key Takeaway: The USER instruction is your primary defense for running containers securely—always create and switch to a non-root user before executing your application to minimize privilege exposure.