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 runcommand 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.
Key facts to keep in mind:
- 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.
- Docker already drops many capabilities: The default set keeps 14, including
NET_RAW,SETUID, andDAC_OVERRIDE. Dropping all and adding back is stricter. - The default seccomp profile is on: It blocks dozens of risky syscalls. Never disable it with
seccomp=unconfined. --privilegedremoves 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.
FROM node:20-alpineWORKDIR /app # Create a fixed, unprivileged user and groupRUN 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=devCOPY --chown=appuser:appgroup dist/ ./dist/ # Everything after this line, including CMD, runs as appuserUSER 10001:10001CMD ["node", "dist/server.js"]The official Node image already contains a node user (UID 1000), so you can skip user creation:
FROM node:20-alpineWORKDIR /appCOPY --chown=node:node package.json package-lock.json ./RUN npm ci --omit=devCOPY --chown=node:node dist/ ./dist/USER nodeCMD ["node", "dist/server.js"]# Verify the userdocker run --rm payment-api:3.1.0 id# uid=10001(appuser) gid=10001(appgroup) # Check what the image is configured to usedocker inspect payment-api:3.1.0 --format '{{.Config.User}}' # Force a user at runtime, regardless of the imagedocker run --rm --user 10001:10001 payment-api:3.1.0 idRememberPrefer 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.
# Drop everythingdocker 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 itdocker run -d --name edge-proxy \ --cap-drop ALL \ --cap-add NET_BIND_SERVICE \ nginx:1.27 # Inspect what was configureddocker inspect payment-api --format 'Add={{.HostConfig.CapAdd}} Drop={{.HostConfig.CapDrop}}'# Add=[] Drop=[ALL] # Confirm inside the container: all zeros means no effective capabilitiesdocker exec payment-api grep CapEff /proc/1/status# CapEff: 0000000000000000Common 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.
# Prove it works: writes faildocker run --rm --read-only alpine touch /test# touch: /test: Read-only file system # Run the app with writable in-memory scratch spacedocker 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.0If 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.
docker run -d \ --name payment-api \ --security-opt no-new-privileges=true \ registry.devops.in/payment-api:3.1.0 # Confirmdocker 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.
# Non-root, read-only, no capabilities, no escalation, default seccomp, limited resourcesdocker 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.0The same settings in Docker Compose:
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: 512MProduction 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 inspectoutput as part of the pipeline.
TipTest 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 MistakePutting
USERbeforeRUN npm ciorchownsteps, so installation fails with permission errors. Install and set ownership first, then switch to the non-root user.
SecurityA
--privilegedcontainer 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 |