Skip to main content

Hardening Docker Containers for Production

Harden Docker containers by running as non-root, dropping Linux capabilities, using read-only filesystems, and blocking privilege escalation.

44 Terms

Overview and What You Will Learn

Docker containers run as root by default, so an attacker who gets code execution in your application starts with root inside the container. You reduce the damage by stacking controls: a non-root user, dropped Linux capabilities, a read-only root filesystem, no-new-privileges, and a seccomp profile. No single control is enough, but together they shrink what a compromised container can do.

In this lab you will:

  • Run a container as a non-root user, in the Dockerfile and at runtime
  • Drop Linux capabilities and add back only what is needed
  • Run with a read-only root filesystem and writable tmpfs mounts
  • Block privilege escalation with no-new-privileges
  • Combine everything into one hardened docker run command and Compose service
  • Verify each control instead of assuming it works

Why This Matters in Production

Imagine an order-matching service at a trading platform like Zerodha with a remote code execution bug. If the container runs as root with default capabilities and a writable filesystem, the attacker can install tools, scan the internal network, and look for a path to the host. A hardened container turns the same bug into a much smaller incident, because there is nowhere to write, nothing to escalate to, and few kernel features to abuse.

Core Principles

Container hardening is defence in depth: each layer assumes the previous one has failed. The goal is a small blast radius when the application is compromised.

flowchart TD A([Attacker exploits app]) --> B[Non-root user] B --> C[Capabilities dropped] C --> D[Read-only filesystem] D --> E[no-new-privileges] E --> G[seccomp syscall filter] G --> F(Limited blast radius) classDef threat fill:#EF4444,color:#FFFFFF classDef control fill:#326CE5,color:#FFFFFF classDef result fill:#10B981,color:#FFFFFF class A threat class B,C,D,E,G control class F result

Key facts to keep in mind:

  1. Root in a container is still root-like: Container root shares the host kernel, so kernel bugs and misconfigurations can turn it into host access.
  2. Docker already drops many capabilities: The default set keeps 14, including NET_RAW, SETUID, and DAC_OVERRIDE. Dropping all and adding back is stricter.
  3. The default seccomp profile is on: It blocks dozens of risky syscalls. Never disable it with seccomp=unconfined.
  4. --privileged removes isolation: It grants all capabilities and host device access, so avoid it.

Detailed Step-by-Step Practical Lab

How to Run a Docker Container as a Non-Root User

You run as non-root by adding a USER instruction to the Dockerfile after installing dependencies. Use an explicit numeric UID so Kubernetes policies and file ownership behave predictably.

Dockerfile
FROM node:20-alpine
WORKDIR /app
# Create a fixed, unprivileged user and group
RUN addgroup -S -g 10001 appgroup && \
adduser -S -u 10001 -G appgroup appuser
COPY --chown=appuser:appgroup package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=appuser:appgroup dist/ ./dist/
# Everything after this line, including CMD, runs as appuser
USER 10001:10001
CMD ["node", "dist/server.js"]

The official Node image already contains a node user (UID 1000), so you can skip user creation:

Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=node:node dist/ ./dist/
USER node
CMD ["node", "dist/server.js"]
Bash
# Verify the user
docker run --rm payment-api:3.1.0 id
# uid=10001(appuser) gid=10001(appgroup)
# Check what the image is configured to use
docker inspect payment-api:3.1.0 --format '{{.Config.User}}'
# Force a user at runtime, regardless of the image
docker run --rm --user 10001:10001 payment-api:3.1.0 id
Remember

Prefer listening on a port above 1024, such as 8080, and map it with -p 80:8080. That way the application needs no special privilege to bind its port.

How to Drop Linux Capabilities in Docker

Capabilities split root's powers into separate permissions. Start from --cap-drop ALL and add back only what a specific workload proves it needs.

Bash
# Drop everything
docker run -d --name payment-api --cap-drop ALL registry.devops.in/payment-api:3.1.0
# Add back one capability if, and only if, the app needs it
docker run -d --name edge-proxy \
--cap-drop ALL \
--cap-add NET_BIND_SERVICE \
nginx:1.27
# Inspect what was configured
docker inspect payment-api --format 'Add={{.HostConfig.CapAdd}} Drop={{.HostConfig.CapDrop}}'
# Add=[] Drop=[ALL]
# Confirm inside the container: all zeros means no effective capabilities
docker exec payment-api grep CapEff /proc/1/status
# CapEff: 0000000000000000

Common capabilities and how to treat them:

Capability What it allows Guidance
NET_BIND_SERVICE Bind ports below 1024 Prefer a high port instead
CHOWN Change file ownership Only for setup scripts
SYS_PTRACE Trace and debug processes Never in production
SYS_ADMIN Broad administration Almost never; very dangerous
How to Run a Docker Container With a Read-Only Filesystem

A read-only root filesystem stops an attacker from dropping tools or modifying application code. Give the app writable tmpfs mounts only for the paths it truly needs.

Bash
# Prove it works: writes fail
docker run --rm --read-only alpine touch /test
# touch: /test: Read-only file system
# Run the app with writable in-memory scratch space
docker run -d \
--name payment-api \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
--tmpfs /run:rw,noexec,nosuid,size=16m \
registry.devops.in/payment-api:3.1.0

If the app crashes with EROFS, find which path it writes to and mount only that path as tmpfs or a volume.

How to Prevent Privilege Escalation With no-new-privileges

The no-new-privileges option stops a process from gaining more privileges than it started with, which neutralises setuid binaries inside the container.

Bash
docker run -d \
--name payment-api \
--security-opt no-new-privileges=true \
registry.devops.in/payment-api:3.1.0
# Confirm
docker inspect payment-api --format '{{.HostConfig.SecurityOpt}}'
# [no-new-privileges=true]
How to Combine All Controls in One Command

This single command applies every control from the lab, plus resource limits. Write the explanation above the command, because inline comments after a line-continuation backslash break the shell.

Bash
# Non-root, read-only, no capabilities, no escalation, default seccomp, limited resources
docker run -d \
--name payment-api \
--user 10001:10001 \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
--cap-drop ALL \
--security-opt no-new-privileges=true \
--memory=512m \
--cpus=1.5 \
-p 8080:8080 \
registry.devops.in/payment-api:3.1.0

The same settings in Docker Compose:

YAML
services:
payment-api:
image: registry.devops.in/payment-api:3.1.0
user: "10001:10001"
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,size=64m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
ports:
- "8080:8080"
deploy:
resources:
limits:
cpus: "1.5"
memory: 512M

Production Best Practices & Common Pitfalls

  • Always set a numeric non-root USER: Do it in the Dockerfile after installing packages.
  • Start from --cap-drop ALL: Add capabilities one at a time and document why.
  • Use read-only root filesystems: Mount tmpfs only for paths that must be writable.
  • Keep the default seccomp profile: Use a custom profile only for a proven need, and never seccomp=unconfined.
  • Never use --privileged: Find the specific capability or device you need instead.
  • Use rootless Docker or user namespaces on shared hosts: They reduce the impact of a container escape.
  • Scan images and verify settings in CI: Check docker inspect output as part of the pipeline.
Tip

Test hardening in staging by enabling controls one at a time. The error message from each failure tells you exactly which write, port, or capability the app depends on.

Common Mistake

Putting USER before RUN npm ci or chown steps, so installation fails with permission errors. Install and set ownership first, then switch to the non-root user.

Security

A --privileged container has access to all host devices, can load kernel modules, and can change host networking. It is effectively root on the host.

Quick Reference & Troubleshooting Commands

Control Flag or setting
Non-root user --user 10001:10001 or USER in the Dockerfile
Drop capabilities --cap-drop ALL
Add one capability --cap-add NET_BIND_SERVICE
Read-only filesystem --read-only
Writable scratch space --tmpfs /tmp:rw,noexec,nosuid,size=64m
Block escalation --security-opt no-new-privileges=true
Check effective capabilities docker exec name grep CapEff /proc/1/status
Symptom Likely cause Fix
EROFS: read-only file system App writes outside allowed paths Mount that path as tmpfs or a volume
permission denied on app files Files owned by root Use COPY --chown or chown before USER
Operation not permitted after dropping caps Missing capability Add only the specific one needed
Cannot bind port 80 as non-root Port below 1024 Listen on 8080 and map the port
App fails to write logs or PID files Read-only root filesystem Log to stdout and add tmpfs for /run

Resources

Explore More in Docker Security and Production Practices

All 5 Topics

Frequently Asked Questions

Is Hardening Docker Containers for Production free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Hardening Docker Containers for Production topic cover?

Harden Docker containers by running as non-root, dropping Linux capabilities, using read-only filesystems, and blocking privilege escalation.

Found a mistake, an outdated step or a broken link?