Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 106 of 8022. Docker Image LifecycleFree lesson

Setting Execution Context with WORKDIR and USER

Learners will enforce security best practices by defining a specific working directory and switching to a non-root user for process execution.

In this lesson, you will learn how to secure your containerized applications by controlling exactly where your code lives and which user identity executes it.

When you build a Docker image, the default behavior is often to place files in the root directory (/) and run processes as the root user. This is a significant security risk; if a malicious actor exploits a vulnerability in your application, they gain administrative control over the container. To prevent this, we use two specific instructions: WORKDIR and USER.

Setting the Context with WORKDIR

The WORKDIR instruction sets the "current directory" for any subsequent RUN, CMD, or ENTRYPOINT instructions. Instead of leaving files scattered in the root, you should define a clear home for your application:

WORKDIR /app
COPY . .

By setting WORKDIR /app, you ensure that all future commands execute relative to that path. If the directory doesn’t exist, Docker will create it for you automatically.

Locking Down Permissions with USER

By default, Docker containers run as the root user. Following the "Principle of Least Privilege," you should switch to a non-privileged user. First, you create a user, and then you use the USER instruction to switch to that identity:

RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

Once you define USER appuser, every command that follows—including the final application start-up—will execute with the restricted permissions of that user. If an attacker manages to break out of your application code, they will be trapped under a user account with limited system access, unable to modify system files or install malicious packages.

By combining these two, you ensure your application runs in a clean, predictable directory and operates with the minimum amount of privilege necessary to function.

Key Takeaway: Always define a specific WORKDIR for your application files and use USER to switch to a non-root account to minimize your container's security attack surface.