Sub topic 2
Running Hardened Containers
Assume you can build and run Docker images, write basic Dockerfiles, and use Linux users and permissions. This chapter covers four controls that reduce the impact of a compromised application: non-root execution, safe secret handling, vulnerability scanning, and reduced capabilities.
Run as a non-root user
A container process runs as root by default. Container root is restricted by namespaces, but a kernel or runtime escape can still turn that privilege into a host-level risk. Create an unprivileged user and make it the process user.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
USER node
CMD ["node", "server.js"]The application must write only to directories owned by node. Avoid granting write access to the whole filesystem. If the image does not provide a suitable user, create one with a fixed UID and GID.
Keep secrets out of images
Never put passwords, tokens, or private keys in Dockerfile ENV or ARG instructions. They can appear in image metadata, build history, or layers. Use a BuildKit secret mount instead.
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci
COPY . .
USER node
CMD ["node", "server.js"]docker build --secret id=npm_token,src=./npm_token.txt -t myapp:1.0 .The token exists only during that build step. At runtime, inject required secrets through a secrets manager or a protected file rather than ordinary environment variables.
Scan images before deployment
Vulnerability scanners compare operating-system packages and application dependencies with vulnerability databases.
trivy image --severity HIGH,CRITICAL myapp:1.0Prioritize reachable vulnerabilities, fixed versions, and exploitable packages. Rebuild regularly because a clean scan is only a point-in-time result.
Drop capabilities
Linux capabilities split root privileges into smaller units. Drop all capabilities unless the application requires a specific one. Do not use --privileged, which grants broad access to devices and kernel features.
docker run --rm \
--user 10001:10001 \
--cap-drop ALL \
--security-opt no-new-privileges \
myapp:1.0Exercise
Why should you use both USER node and --cap-drop ALL?
Show answer
USER reduces the process identity's baseline privilege, while --cap-drop ALL removes separate kernel privileges that could otherwise remain available.