Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 111 ยท Security

A Container Security Checklist

A practical Docker security checklist for the build, ship and run stages, with commands that verify each item and a small audit script you can run on any container.

The previous lessons covered the pieces one by one: the threat model, users and capabilities, image scanning, secrets, seccomp and read-only filesystems and the daemon. Knowing them is one thing; applying them consistently to every project is another. This lesson turns them into a checklist you can copy into a pull-request template, together with the commands that prove each item instead of trusting it.

The list has three stages, because mistakes are cheapest to fix in the earliest one: build (what goes into the image), ship (how it travels), and run (how the container starts). At the end you will get a short audit script that reads a running container's settings and prints the ones that matter. Everything was verified on Docker 29; the sample app is a tiny Python web server built from a pinned python:3.13-slim image.

TEXT
   BUILD                       SHIP                        RUN
 +-------------+          +---------------+          +----------------+
 | small base  |  image   | scan, sign,   |  image   | non-root       |
 | pinned      | -------> | immutable tag | -------> | read-only      |
 | no secrets  |          | private repo  |          | few caps, limits|
 +-------------+          +---------------+          +----------------+
   Dockerfile                registry                  docker run / Compose

Stage 1: build

1. Start from a trusted, minimal, pinned base

Use an official or verified image, as small as your app allows (-slim, Alpine or distroless; see Choosing a Base Image). Fewer packages mean fewer vulnerabilities and fewer tools for an attacker. Then pin it. A tag like 3.13-slim moves whenever the maintainers publish a rebuild; a digest never does:

CONSOLE
$ docker buildx imagetools inspect python:3.13-slim --format '{{.Manifest.Digest}}'
sha256:57b29a7c050c4e679e4bea572e14b3965cf4b5839de2da49d55e49ffc4024f39
DOCKERFILE
FROM python:3.13-slim@sha256:57b29a7c050c4e679e4bea572e14b3965cf4b5839de2da49d55e49ffc4024f39

(The digest changes as the tag is rebuilt; yours will differ.) Pinning trades automatic security patches for reproducibility, so pair it with a tool that opens a pull request when a new digest appears (Renovate or Dependabot) and a scheduled rebuild.

2. Create a non-root user and switch to it

Without a USER line the process runs as root. Create a user with a fixed numeric ID, give it no login shell and no home directory, and switch to it after the last step that needs root:

DOCKERFILE
FROM python:3.13-slim@sha256:57b29a7c050c4e679e4bea572e14b3965cf4b5839de2da49d55e49ffc4024f39
RUN groupadd --gid 10001 app \
 && useradd --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
WORKDIR /srv
COPY --chown=app:app app.py .
USER app
EXPOSE 8000
HEALTHCHECK --interval=5s --timeout=2s --retries=3 \
  CMD ["python", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8000')"]
CMD ["python", "app.py"]

A numeric ID matters because Kubernetes policies such as runAsNonRoot can only verify a number, not a name. The HEALTHCHECK lets orchestrators notice a hung process. The build and the result, checked from outside:

CONSOLE
$ docker build -q -t web:1.0.0 .
sha256:aa6a1587dcfb...
$ docker run --rm web:1.0.0 id
uid=10001(app) gid=10001(app) groups=10001(app)
$ docker image inspect web:1.0.0 --format '{{.Config.User}}'
app

3. Keep secrets out of the image

Anything in a RUN, ENV, ARG or copied file becomes part of the image's history, and anyone who can pull the image can read it. Here is what a careless Dockerfile leaks (an ARG token and an ENV password):

CONSOLE
$ docker history leak --no-trunc --format '{{.CreatedBy}}' | grep -E 'API_TOKEN|DB_PASSWORD'
RUN |1 API_TOKEN=abc123 /bin/sh -c echo "built with $API_TOKEN" > /build.txt # buildkit
ENV DB_PASSWORD=hunter2
ARG API_TOKEN=abc123
$ docker image inspect leak --format '{{json .Config.Env}}'
["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","DB_PASSWORD=hunter2"]

Use a BuildKit secret mount for build-time secrets. The value exists only while that one RUN step executes, and the history shows just the command:

CONSOLE
$ docker build --secret id=api_token,src=tok.txt --progress=plain -t sec .
#7 [stage-0 2/2] RUN --mount=type=secret,id=api_token sh -c 'wc -c < /run/secrets/api_token'
#7 0.582 6
$ docker history sec --no-trunc --format '{{.CreatedBy}}' | head -1
RUN /bin/sh -c sh -c 'wc -c < /run/secrets/api_token' # buildkit

The step read the six bytes of the secret (the 6 line), and the token itself appears nowhere in the history. Run-time secrets are covered in Managing Secrets.

4. Use a .dockerignore and copy only what you need

The build context is sent to the builder; a careless COPY . . can put .git, .env files and private keys in a layer. Exclude them, and prefer copying specific paths. See Build Context and .dockerignore.

TEXT
.git
.env
*.pem
node_modules

5. Multi-stage builds

Compilers, package managers and test tools belong in a build stage, not in the image you run. Copy only the finished artifact into a minimal final stage (Multi-Stage Builds). The final image then has fewer packages to patch and fewer programs for an attacker to use.

6. Lint the Dockerfile

A linter catches mistakes such as latest tags, missing USER lines and apt-get without cleanup. This is a read-only example; it needs the tool installed:

CONSOLE
$ hadolint Dockerfile
Dockerfile:1 DL3007 warning: Using latest is prone to errors if the image will ever update...

Docker's own docker build --check runs a built-in set of such rules, and you can add either to CI so the build fails on violations.

Stage 2: ship

7. Scan the image, and rescan it on a schedule

New vulnerabilities are published every day against old images. Scan at build time to fail on critical findings, and again nightly for images that are deployed but not rebuilt. Scanners (Trivy, Grype, Docker Scout) are covered in Image Security and Scanning. A typical CI line is a read-only example:

Terminal
trivy image --severity HIGH,CRITICAL --exit-code 1 registry.example.com/team/web:1.0.0

8. Tag immutably and deploy by version or digest

Never deploy latest. Use a version (1.0.0) or the commit SHA, treat published tags as immutable, and for the strictest control deploy by digest. See Tagging and Versioning Strategies.

9. Sign images and generate an SBOM

A signature proves who built an image; a software bill of materials (SBOM) lists what is in it, so you can answer "are we affected?" the day a new vulnerability is announced. BuildKit can attach an SBOM and provenance during the build (--sbom=true --provenance=mode=max), and Cosign signs the result. Both are read-only examples here because they need a registry:

Terminal
docker buildx build --sbom=true --provenance=mode=max -t registry.example.com/team/web:1.0.0 --push .
cosign sign registry.example.com/team/web@sha256:<digest>

10. Use a private registry with least-privilege access

CI should hold a token that can push to one repository; production hosts should hold a token that can only pull. Rotate tokens, and never reuse a personal login. See Working with Registries and Running a Private Registry.

Stage 3: run

11. Drop what you do not need

Start from the strictest settings and add back only what fails:

CONSOLE
$ docker run -d --name web --read-only --cap-drop ALL \
    --security-opt no-new-privileges --pids-limit 100 --memory 128m \
    -p 127.0.0.1:8080:8000 web:1.0.0
Flag What it does
--read-only Root filesystem is not writable (add --tmpfs for scratch paths)
--cap-drop ALL Removes every Linux capability; add back only specific ones
--security-opt no-new-privileges Blocks privilege gain through setuid programs
--pids-limit, --memory, --cpus Stop a runaway process or fork bomb from starving the host
-p 127.0.0.1:8080:8000 Publishes the port only on the loopback interface

The Compose version of the same settings is read_only: true, cap_drop: [ALL], security_opt, pids_limit, mem_limit and ports with the host address in front. Never use --privileged, never use --network host without a strong reason, and never mount the Docker socket (Securing the Docker Daemon).

12. Publish as few ports as possible, and bind them deliberately

A port published as -p 8080:80 listens on every interface of the host, often including the public one, and Docker's firewall rules bypass tools such as ufw. Bind to 127.0.0.1 when a reverse proxy on the same host is the only client, and keep databases off the host network entirely by letting them talk to the app over a private network (Publishing Ports).

13. Separate networks, not one big one

Put the database on a network that only the API shares. A compromised front end then cannot reach it directly (User-Defined Bridge Networks).

14. Log, monitor, and keep the host patched

Rotate logs (max-size, max-file), ship them somewhere an attacker cannot erase, and watch for containers that restart repeatedly. The kernel and the Docker Engine are the foundation under every container; a container escape is almost always a kernel or runtime bug, so patch them.

An audit script

A checklist is only useful if it is checked. This short script prints the security-relevant settings of running containers, using nothing but docker inspect and a Go template:

Terminal
#!/bin/sh
# usage: ./audit.sh <container>...
for c in "$@"; do
  docker inspect "$c" --format '{{.Name}}
  user:        {{if .Config.User}}{{.Config.User}}{{else}}(root){{end}}
  privileged:  {{.HostConfig.Privileged}}
  read-only:   {{.HostConfig.ReadonlyRootfs}}
  cap-drop:    {{.HostConfig.CapDrop}}
  security:    {{.HostConfig.SecurityOpt}}
  memory:      {{.HostConfig.Memory}}
  pids-limit:  {{if .HostConfig.PidsLimit}}{{.HostConfig.PidsLimit}}{{else}}none{{end}}
  health:      {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}
  ports:       {{range $p, $b := .NetworkSettings.Ports}}{{$p}}->{{range $b}}{{.HostIp}}:{{.HostPort}} {{end}}{{end}}'
done

Run against one container started with the strict flags from item 11 and one started carelessly (as root, no limits):

CONSOLE
$ sh audit.sh good bad
/good
  user:        app
  privileged:  false
  read-only:   true
  cap-drop:    [ALL]
  security:    [no-new-privileges]
  memory:      134217728
  pids-limit:  100
  health:      healthy
  ports:       8000/tcp->127.0.0.1:18112
/bad
  user:        0
  privileged:  false
  read-only:   false
  cap-drop:    <no value>
  security:    <no value>
  memory:      0
  pids-limit:  none
  health:      healthy
  ports:       8000/tcp->127.0.0.1:18113

Read the second block the way a reviewer would: root user (0), writable filesystem, no dropped capabilities, no no-new-privileges, and no memory or process limit. The memory value is in bytes (134217728 is 128 MiB), and 0 means unlimited. The ports line is where you look for 0.0.0.0; here the careless container was bound to loopback too, to keep the experiment private. The strict container really is restricted:

CONSOLE
$ docker exec good id
uid=10001(app) gid=10001(app) groups=10001(app)
$ docker exec good touch /srv/x
touch: cannot touch '/srv/x': Read-only file system
$ curl -s http://127.0.0.1:18112/
ok

It still serves traffic. Hardening should be invisible to users and visible to attackers.

Put the audit in CI for your Compose files with docker compose config and a few grep or yq checks (privileged: true, docker.sock, network_mode: host, latest), so a risky change fails a pull request before it reaches a server.

Common mistakes professionals still make

  • Treating a scan with zero findings as proof of safety. Scanners only know published vulnerabilities in packages they can identify.
  • Hardening the container but exposing the daemon on TCP, or adding every developer to the docker group.
  • Using USER root "temporarily" in the final stage and forgetting to switch back.
  • Putting the same secret in every environment, so one leak compromises production.
  • Skipping updates because "the image is pinned", which pins the vulnerabilities too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Dockerfile contains ENV DB_PASSWORD=hunter2. Who can read that value?

    ENV values are stored in the image configuration and visible in the history. Use run-time secrets or a BuildKit secret mount for build-time secrets.
  2. 2. Which pin is the most reproducible way to select a base image?

    A tag can be moved to a new image when maintainers republish; a digest identifies exactly one image, forever.
  3. 3. In the audit output, which line would show that a container is reachable from other machines?

    A host IP of 0.0.0.0 means the published port listens on every interface; 127.0.0.1 restricts it to the machine itself.
  4. 4. Why use numeric IDs like 10001 in the Dockerfile's USER setup?

    An orchestrator cannot tell from a user name whether it maps to root. A non-zero numeric UID is verifiable.
  5. 5. Which stage of the checklist is the cheapest place to fix a vulnerable package?

    A problem caught at build time never reaches a registry or a server, so there is nothing to recall, redeploy or investigate.

Summary

  • Apply security in three stages: build (small pinned base, non-root user, no secrets, multi-stage, .dockerignore, lint), ship (scan, immutable tags, signatures and SBOMs, least-privilege registry tokens) and run (read-only, --cap-drop ALL, no-new-privileges, limits, loopback-bound ports, separate networks).
  • Verify instead of trusting: docker history, docker image inspect and docker inspect show what an image or container really contains and how it runs.
  • Secrets in ENV, ARG or RUN end up in the image history; use BuildKit secret mounts at build time.
  • A digest pin gives reproducibility, so automate updates to keep security patches flowing.
  • Hardening is layered: no single setting is enough, and none should break the application's behavior.
  • Automate the checks in CI so the checklist is enforced, not remembered.

Next: Working with Registries