Skip to content

For more context on confinement and sandboxing through Docker you can check my "Notes on system security". This is just a practical cheat sheet for docker hardening.

Docker Hardening Checklist

OCI reminder

To create a container you need a way to describe the image, and a way to run the process from it in memory. Both are standardized by the Open Container Initiative (OCI) : - Build an image (OCI builder) : Dockerfile, apko, Bazel, Nix - Run an image (OCI runtime) : Docker, Kubernetes (which call an OCI runtime like runc under the hood)

This checklist follows the same split.

Build (Dockerfile)

Don't run as root

Why run any service as root in the container when you can create a user ?

FROM python:3.12-slim

RUN adduser --disabled-password --gecos "" worker

USER worker
WORKDIR /home/worker

COPY --chown=worker:worker . .

CMD ["python3", "main.py"]

Pin images by digest

Tags are mutable : python:3.12-slim can point to another image tomorrow. The digest identifies exactly one image, so reference images by digest, in the FROM as well as in the deployment manifests :

$ docker buildx imagetools inspect python:3.12-slim
Name:      docker.io/library/python:3.12-slim
MediaType: application/vnd.oci.image.index.v1+json
Digest:    sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
FROM python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1

The examples in this doc use tags to stay readable, in a real Dockerfile use digests.

Multi-stage build

When deploying the application requires a compilation step (like Go binaries, although this can also apply to Python, which can be "pseudo-compiled"), the tools used for compilation aren't needed in the container and only add unnecessary risk. So you can simply copy the compiled binary into the final container :

FROM golang:1.25-alpine AS builder

WORKDIR /app

ENV CGO_ENABLED=0 GOOS=linux GOARCH=amd64

COPY go.mod go.sum ./

RUN go mod download

COPY . .

RUN go build -trimpath -ldflags="-s -w" -o myapp .


FROM alpine:3.22

WORKDIR /app

COPY --from=builder /app/myapp /app/myapp

ENTRYPOINT ["/app/myapp"]

No secrets in the image

Everything that goes through ENV, ARG or COPY stays in the image layers, even if a later RUN deletes it :

$ docker build --build-arg TOKEN=s3cr3t -t demo:arg .
$ docker history --no-trunc --format '{{.CreatedBy}}' demo:arg | grep TOKEN
RUN |1 TOKEN=s3cr3t /bin/sh -c echo "using $TOKEN" > /dev/null # buildkit
ARG TOKEN=s3cr3t

Use a BuildKit secret instead, it's only mounted during the RUN and never written in a layer :

RUN --mount=type=secret,id=token TOKEN=$(cat /run/secrets/token) && ...
$ docker build --secret id=token,src=token.txt -t demo:secret .
$ docker history --no-trunc demo:secret | grep -c s3cr3t
0

.dockerignore

The COPY . . of the non-root example copies the whole build context into the image, including .git, .env, keys etc... A .dockerignore file excludes them :

.git
.env
*.key
*.pem

Docker SBOM and dependency tracking

Docker SBOM (Software Bill of Materials) lists the image's OS packages, libraries, dependencies, etc... to give a complete view of the software dependency chain.

$ docker scout sbom nginx:latest > sbom_nginx_latest
{"level":"info","msg":"SBOM of image already cached, 233 packages indexed\n","time":"2026-01-27T11:49:27+01:00"}

$ head sbom_nginx_latest
{
  "source": {
    "type": "image",
    "image": {
      "name": "nginx",
      "digest": "sha256:617fef3c6adb90788d06f7ebe634fe990a6cd1e63c815facaf5fcaf3fa1ea003",
      "tags": [
        "latest"
      ],
      "manifest": {

Once the SBOM is generated, you can track in real time how the CVEs tied to the software versions in the image's supply chain evolve, thanks to SCA.

Keep the SBOM file in the repository : the dependencies of the image and those of the application are then tracked in the same place.

SCA analysis

SCA (Software Composition Analysis) takes the inventory of the image (the SBOM) and checks every package against vulnerability databases (NVD, GitHub advisories, distro security trackers etc...).

Example with Grype on the official Python image :

$ grype python:3.12-slim
NAME          INSTALLED         FIXED IN                    TYPE    VULNERABILITY   SEVERITY  EPSS         RISK
perl-base     5.40.1-6+deb13u1  (won't fix)                 deb     CVE-2026-82560  High      0.6% (49th)  0.5
libncursesw6  6.5+20250216-2    (won't fix)                 deb     CVE-2025-69720  High      0.5% (38th)  0.4
libtinfo6     6.5+20250216-2    (won't fix)                 deb     CVE-2025-69720  High      0.5% (38th)  0.4
ncurses-base  6.5+20250216-2    (won't fix)                 deb     CVE-2025-69720  High      0.5% (38th)  0.4
ncurses-bin   6.5+20250216-2    (won't fix)                 deb     CVE-2025-69720  High      0.5% (38th)  0.4
perl-base     5.40.1-6+deb13u1  (won't fix)                 deb     CVE-2026-9538   High      0.4% (37th)  0.3
python        3.12.15           *3.13.10, 3.14.1, 3.15.0a2  binary  CVE-2025-12781  Medium    0.6% (45th)  0.3
...

The useful part is to run it in the CI and break the build when a vulnerability above a threshold is found :

$ grype python:3.12-slim --fail-on high
[0129] ERROR discovered vulnerabilities at or above the severity threshold

Grype can also scan the SBOM from the previous step directly (grype sbom:./sbom.spdx.json).

Most of the results are (won't fix) packages of the base image that the app never uses (perl, ncurses...). You can't patch them, the only way to get rid of them is to remove them from the image, see distroless below.

Distroless (Chainguard)

A distroless image only contains the application and its runtime : no shell, no package manager, no coreutils. Fewer packages means fewer CVEs, and an attacker who gets code execution has no tools to work with.

Chainguard images (cgr.dev/chainguard/...) are distroless images rebuilt every day, and they run as a non-root user by default (nonroot, uid 65532). Same Python, same scan as above :

$ grype python:3.12-slim -q -o json | jq '.matches | length'
172

$ grype cgr.dev/chainguard/python:latest -q -o json | jq '.matches | length'
0

It fits well with the multi-stage build : the Go binary is static (CGO_ENABLED=0), so the final stage only needs static, which is basically just CA certificates and /etc/passwd :

FROM golang:1.25-alpine AS builder
# ... same builder stage as above

FROM cgr.dev/chainguard/static:latest

COPY --from=builder /app/myapp /app/myapp

ENTRYPOINT ["/app/myapp"]

With the vulnerable app from the seccomp section on a Chainguard base :

FROM cgr.dev/chainguard/python:latest
WORKDIR /app
COPY app.py .
ENTRYPOINT ["python", "app.py"]
$ docker run --rm -d --name distroless -p 127.0.0.1:8000:8000 demo:distroless

$ curl -sG localhost:8000/calc --data-urlencode "e=__import__('os').popen('id').read()"
error: FileNotFoundError(2, 'No such file or directory')

$ curl -sG localhost:8000/calc --data-urlencode "e=__import__('os').getuid()"
65532

$ docker exec distroless sh
OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH: unknown

Distroless doesn't fix the RCE : the attacker can still run Python code (open('/etc/passwd').read() still works). It only takes away the tools around it, so it goes with seccomp and the rest, not instead of them.

Chainguard also open-sourced the tools used to build these images, so you can build your own distroless images instead of pulling them from a public registry. Here is how distroless works at Chainguard :

  • Wolfi : an "undistro". It has nothing but a package system, and the filesystem is only assembled at the end of the build.

  • APK (Alpine Package Keeper) : the package manager Wolfi uses to download its dependencies and resolve them recursively (ask for Python 3 and you get everything it needs, the dependencies of the dependencies, etc...). It avoids building and maintaining a "from scratch" image with imported binaries. Then either you maintain your own APK repository, or you trust Chainguard's, which has a good reputation for security.

  • apko : turns a declarative YAML file into an OCI image.

Example with a Python base image :

contents:
  repositories:
    - https://packages.wolfi.dev/os
  keyring:
    - https://packages.wolfi.dev/os/wolfi-signing.rsa.pub
  packages:
    - python-3.12

accounts:
  groups:
    - groupname: nonroot
      gid: 65532
  users:
    - username: nonroot
      uid: 65532
      gid: 65532
  run-as: 65532

entrypoint:
  command: /usr/bin/python3

archs:
  - x86_64
$ apko build apko.yaml demo:apko demo.tar
...
2026/10/20 16:54:02 INFO installing python-3.12-base (3.12.15-r4) arch=x86_64
2026/10/20 16:54:02 INFO installing python-3.12 (3.12.15-r4) arch=x86_64
...

$ ls
apko.yaml  demo.tar  sbom-index.spdx.json  sbom-x86_64.spdx.json

$ docker load < demo.tar
Loaded image: demo:apko-amd64

The result is a 66 MB image without shell, running as uid 65532 (vs 119 MB for python:3.12-slim). apko also generates the SBOM of the image at build time (sbom-*.spdx.json), ready to be committed in the repository.

Why not just use Alpine Linux ? - Alpine is still a "classic" Linux distribution, you can use it on a VM for example - Wolfi is much smaller (almost empty)

Google's gcr.io/distroless/* images are the other common option.

Signing

Signing proves that the image running in production is the one your CI built, and that nobody changed it in the registry in between (compromised registry, someone pushing another image on the same tag...). Tags are mutable, a signature is tied to the image digest.

Example with cosign (Sigstore) on a local registry :

$ docker push localhost:5000/myapp:1.0

$ cosign generate-key-pair
Private key written to cosign.key
Public key written to cosign.pub

$ cosign sign --key cosign.key --tlog-upload=false localhost:5000/myapp@sha256:5f04e29ef7f1b4021250c07bbc8921a944d2df5e604069976c820d90877d18e1
Pushing signature to: localhost:5000/myapp

$ cosign verify --key cosign.pub --insecure-ignore-tlog=true localhost:5000/myapp@sha256:5f04e29ef7f1b4021250c07bbc8921a944d2df5e604069976c820d90877d18e1
WARNING: Skipping tlog verification is an insecure practice that lacks of transparency and auditability verification for the signature.

Verification for localhost:5000/myapp@sha256:5f04e29ef7f1b4021250c07bbc8921a944d2df5e604069976c820d90877d18e1 --
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key

[{"critical":{"identity":{"docker-reference":"localhost:5000/myapp"},"image":{"docker-manifest-digest":"sha256:5f04e29ef7f1b4021250c07bbc8921a944d2df5e604069976c820d90877d18e1"},"type":"cosign container image signature"},"optional":null}]

Now someone pushes another image on the same tag :

$ docker tag cgr.dev/chainguard/static:latest localhost:5000/myapp:1.0
$ docker push localhost:5000/myapp:1.0

$ cosign verify --key cosign.pub --insecure-ignore-tlog=true localhost:5000/myapp:1.0
Error: no signatures found

The --tlog-upload=false / --insecure-ignore-tlog=true flags are only there because this is a local demo. By default cosign also records the signature in Rekor, a public transparency log, so you can audit every signature that was made with your key.

In a CI you don't even need to manage a key : keyless signing (cosign sign <image>@<digest> without --key) uses the OIDC identity of the job (GitHub Actions, GitLab CI...), and you verify it with --certificate-identity and --certificate-oidc-issuer. The SBOM can be attached to the image the same way, signed : cosign attest --key cosign.key --type spdxjson --predicate sbom.spdx.json <image>@<digest>.

Signing is useless if nobody checks it : on Kubernetes, an admission controller (Sigstore policy-controller, Kyverno verifyImages) refuses to start images that aren't signed.

Provenance

Signing proves who published the image, provenance (SLSA) proves how it was built : from which repository and commit, with which Dockerfile and build args. BuildKit attaches it to the image in the registry, along with the SBOM :

$ docker buildx build --provenance=mode=max --sbom=true -t registry.example.com/myapp:1.0 --push .

$ docker buildx imagetools inspect registry.example.com/myapp:1.0 --format '{{ json .Provenance.SLSA }}'

mode=max includes the build args, one more reason to never pass secrets with ARG.

Run (Docker Compose / Kubernetes / Swarm)

Don't use --privileged

With --privileged on the container, a root user in the container is also root on the host machine.

Among other things, they can mount the host filesystem inside the container.

Don't mount the Docker socket

Access to /var/run/docker.sock means control of the Docker daemon, which runs as root. From a container that has the socket, you can start another container that mounts the host filesystem :

$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock docker:cli \
    docker run --rm -v /etc:/host-etc alpine:3.22 wc -c /host-etc/shadow
1127 /host-etc/shadow

If a tool really needs it (Traefik, Portainer...), put a socket proxy in front that only exposes the API calls it needs.

no-new-privileges

Blocks any privilege gain after the container starts, typically through a setuid binary like su or sudo. Goes with the non-root user and the capabilities drop :

security_opt:
  - no-new-privileges:true

Read-only filesystem

The attacker can't drop a binary or modify the app. The directories the app needs to write go in a tmpfs :

read_only: true
tmpfs:
  - /tmp
$ docker run --rm --read-only alpine:3.22 touch /pwned
touch: /pwned: Read-only file system

Secrets at runtime

Environment variables leak (docker inspect, /proc/<pid>/environ, logs), and so do command line arguments (visible with ps on the host). Mount secrets as files instead, they end up in /run/secrets/ :

services:
  app:
    image: "random_image"
    secrets:
      - db_password

secrets:
  db_password:
    file: ./db_password.txt

Limit RAM and CPU

services:
  redis:
    image: "redis:alpine"
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: "64M"

Separate networks

services:
  container1:
    image: "random_image"
    networks:
      - intern
  container2:
    image: "random_image"
    networks:
      - intern
      - public

networks:
  intern:
    driver: bridge
    internal: true # <--- block internet access
  public:
    driver: bridge
container1 <-> container2
container2 <-> internet

Bind ports to localhost

By default -p 8000:8000 listens on all interfaces, and Docker's iptables rules bypass UFW / firewalld : anyone on the LAN can reach the app. Binding to 127.0.0.1 means only the host has access, handy for tests :

ports:
  - "127.0.0.1:8000:8000"

Drop capabilities

Capabilities split root's powers into small, independent privileges. A service can be given only the rights it needs.

Most of the time containers don't need any capabilities (especially if everything happens inside the container).

cap_drop:
  - ALL

Filter syscalls (seccomp)

Where namespaces restrict what the process sees, seccomp restricts what the process can ask the kernel (it filters the syscalls). And the tool it uses for this task is BPF (Berkeley Packet Filter); see my article on eBPF for the details.

It is used in particular for Docker hardening : by default Docker allows about 300 syscalls, but what we will do is start the process with strace to know the syscalls it needs and only allow those ones. This way if an attacker manages to manipulate the process, they will not really be able to do other actions than the planned and allowed ones.

Example with a vulnerable application :

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

class H(BaseHTTPRequestHandler):
    def do_GET(self):
        u = urlparse(self.path)
        try:
            if u.path == "/calc":
                body = str(eval(parse_qs(u.query)["e"][0])) # RCE
            else:
                body = "hello"
            self.send_response(200)
        except Exception as e:
            body = f"error: {e!r}"
            self.send_response(500)
        self.end_headers()
        self.wfile.write((body + "\n").encode())

HTTPServer(("0.0.0.0", 8000), H).serve_forever()
FROM python:3.12-alpine AS app
WORKDIR /app
COPY app.py .
CMD ["python", "app.py"]

FROM app AS trace
RUN apk add --no-cache strace

Build both targets :

docker build --target app   -t demo:app   .
docker build --target trace -t demo:trace .

Run the app and we can exploit the RCE :

$ docker run --rm -d --name open -p 127.0.0.1:8000:8000 demo:app

$ curl -sG localhost:8000/calc --data-urlencode "e=1+1"
2

$ curl -sG localhost:8000/calc --data-urlencode "e=__import__('os').popen('id').read()"
uid=0(root) gid=0(root) groups=0(root),...

Trace the syscalls while exercising the app :

$ docker run -d --name trace --cap-add SYS_PTRACE -p 127.0.0.1:8000:8000 -v "$PWD":/out demo:trace timeout 12 strace -f -o /out/trace.txt python app.py

$ curl -s localhost:8000/
$ curl -sG localhost:8000/calc --data-urlencode "e=1+1"
$ curl -sG localhost:8000/calc --data-urlencode "e=1/0"

$ docker kill trace && docker rm trace

$ head trace.txt
10    execve("/usr/local/bin/python", ["python", "app.py"], 0x7ffc0fa563c0 /* 7 vars */) = 0
10    arch_prctl(ARCH_SET_FS, 0x709ac28cab28) = 0
10    set_tid_address(0x709ac28caf90)   = 10
10    brk(NULL)                         = 0x55d34a6ba000
10    brk(0x55d34a6bc000)               = 0x55d34a6bc000
10    mmap(0x55d34a6ba000, 4096, PROT_NONE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x55d34a6ba000
10    readlink("/proc/self/exe", "/usr/local/bin/python3.12", 512) = 25
10    open("/usr/local/bin/../lib/libpython3.12.so.1.0", O_RDONLY|O_LARGEFILE|O_CLOEXEC) = 3
10    fcntl(3, F_SETFD, FD_CLOEXEC)     = 0
10    fstat(3, {st_mode=S_IFREG|0755, st_size=7236576, ...}) = 0

Extract the list of unique syscalls :

$ sed -nE 's/^[0-9]+ +([a-z_0-9]+)\(.*/\1/p' trace.txt | sort -u > syscalls.txt

$ cat syscalls.txt
accept4
arch_prctl
bind
brk
close
epoll_create1
execve
fcntl
fstat
getcwd
...

Write profile.json with these syscalls :

{
  "defaultAction": "SCMP_ACT_ERRNO",
  "syscalls": [
    {
      "names": [
        "accept4",
        "access",
        "arch_prctl",
        "bind",
        "brk",
        "capget",
        "capset",
        "chdir",
        ...
        "unlinkat",
        "wait4",
        "write",
        "writev"
      ],
      "action": "SCMP_ACT_ALLOW"
    }
  ]
}

Run with the seccomp profile and we can no longer exploit the vulnerability :

$ docker run --rm --name test -p 127.0.0.1:8000:8000 --security-opt seccomp=$PWD/profile.json demo:app

$ curl -sG localhost:8000/calc --data-urlencode "e=1+1"
2

$ curl -sG localhost:8000/calc --data-urlencode "e=__import__('os').popen('id').read()"
error: PermissionError(1, 'Operation not permitted')

$ curl -sG localhost:8000/calc --data-urlencode "e=__import__('socket').create_connection(('127.0.0.1',8000))"
error: PermissionError(1, 'Operation not permitted')

By default, a Linux process has no seccomp filter. It is the software itself, or its launcher, that decides to restrict itself. Browsers do it, or OpenSSH for example.

User namespaces / rootless

Without user namespaces, root in the container is uid 0 on the host : if it escapes, it's root on the host. With userns-remap, container uids are mapped to unprivileged uids on the host (root becomes 100000 for example). In /etc/docker/daemon.json :

{
  "userns-remap": "default"
}

Or go further with rootless Docker (or Podman), where the daemon itself doesn't run as root.

Host and daemon

  • Keep the kernel, runc and Docker up to date : container escapes go through them (runc CVE-2024-21626 "Leaky Vessels" for example).
  • Never expose the Docker API over TCP without TLS (port 2375) : it's a remote root shell.
  • Being in the docker group is equivalent to being root on the host (see the Docker socket above).

Checklist

Build

  • [ ] The service runs as a dedicated non-root user (USER)
  • [ ] Images referenced by digest (FROM image@sha256:...)
  • [ ] Multi-stage build : compilers and build tools stay in the builder stage, only the binary ships
  • [ ] No secrets in ENV, ARG or COPY (BuildKit secrets instead)
  • [ ] .dockerignore excludes .git, .env and keys
  • [ ] SBOM generated (docker scout sbom) and committed in the repository
  • [ ] SCA scan in the CI that breaks the build above a severity threshold (grype --fail-on high)
  • [ ] Distroless base image (Chainguard, or built in-house with apko), pinned by digest
  • [ ] Image signed by digest (cosign sign) and signature verified at deploy time
  • [ ] Provenance and SBOM attached to the image

Run

  • [ ] No --privileged
  • [ ] No Docker socket mounted in a container
  • [ ] no-new-privileges set
  • [ ] Read-only root filesystem
  • [ ] Secrets mounted as files, not in environment variables
  • [ ] CPU and memory limits set
  • [ ] Networks separated, internal-only networks marked internal: true
  • [ ] Ports bound to 127.0.0.1 when the app doesn't need to be reachable from the LAN
  • [ ] All capabilities dropped (cap_drop: [ALL])
  • [ ] Seccomp profile that only allows the syscalls the app needs (--security-opt seccomp=profile.json)
  • [ ] User namespaces or rootless Docker
  • [ ] Kernel, runc and Docker up to date, Docker API not exposed, docker group restricted