Day 17intermediateFeb 17, 2026

Never Run Containers as Root

Running as root inside a container means a breakout may give an attacker elevated privileges on your host.

dockersecuritybest-practices
Share:

What

By default, Docker containers run processes as the root user (UID 0). This is a significant security risk because if an attacker escapes the container, they may have elevated privileges on the host system. Adding a USER instruction in your Dockerfile runs the process as a non-privileged user instead.

Why It Matters

Container breakout vulnerabilities are real and well-documented. Running as root violates the principle of least privilege and expands the blast radius of any exploit. Many compliance frameworks and security scanners flag root containers as a critical vulnerability.

Example

# Dockerfile with non-root user
FROM node:20-slim

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .

# Create a non-root user and group
RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser

# Change ownership of app files
RUN chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

EXPOSE 3000
CMD ["node", "server.js"]
dockerfile

Common Mistake

Switching to a non-root user before installing dependencies or changing file ownership. The new user won't have permission to write to directories or install packages, causing build failures.

Quick Fix

Always create the user, install dependencies, set file ownership with chown, and THEN switch to the non-root user with USER as one of the last instructions in your Dockerfile.

Key Takeaways

  • 1Default Docker user = root (UID 0)
  • 2Container breakout + root = elevated host risk
  • 3Create user: useradd -r -g appuser appuser
  • 4Set ownership: chown -R appuser:appuser /app
  • 5Switch last: USER appuser (after installs)

Was this tip helpful?

Help us improve the DevOpsPath daily collection

Share: