Docker container hardening

How to shrink what a compromised process can do inside a container.

A container is just a process

There is no separate machine. A container is a regular host process, running on the same kernel as everything else. What makes it look isolated are a few filters the kernel applies around it. If someone breaks into the app, the possible damage is exactly what those filters let through.

Processin the containermount(...)seccompdoes this syscallexist for me?capabilitiesam I privilegedto do this?namespaceswhat do Iget to see?Kernelfiles, network,processesEPERMEPERMdoes not deny:shows only thecontainer's worldcgroupsaround everything: how many processes, how much memory and CPU the container can use
Each filter answers a different question. None of them replaces the others.
The idea in one sentence: hardening means tightening each of these filters until the process has only what it needs, and then proving, with one command, that the running container really is like that.

Capabilities: root in pieces

Linux does not treat root as a single block. Its powers are split into some forty capabilities: changing a file's owner (CHOWN), opening a raw socket (NET_RAW), mounting file systems (SYS_ADMIN) and so on. Every process has a bounding set, which is the ceiling: nothing outside it can be gained, not even by running a setuid binary.

Docker already cuts a lot by default and hands out 14. The recipe is to cut down to zero and give back only what a service provably uses. Hover over a square to see its name.

privileged: true000001ffffffffffCAP_CHOWNCAP_DAC_OVERRIDECAP_DAC_READ_SEARCHCAP_FOWNERCAP_FSETIDCAP_KILLCAP_SETGIDCAP_SETUIDCAP_SETPCAPCAP_LINUX_IMMUTABLECAP_NET_BIND_SERVICECAP_NET_BROADCASTCAP_NET_ADMINCAP_NET_RAWCAP_IPC_LOCKCAP_IPC_OWNERCAP_SYS_MODULECAP_SYS_RAWIOCAP_SYS_CHROOTCAP_SYS_PTRACECAP_SYS_PACCTCAP_SYS_ADMINCAP_SYS_BOOTCAP_SYS_NICECAP_SYS_RESOURCECAP_SYS_TIMECAP_SYS_TTY_CONFIGCAP_MKNODCAP_LEASECAP_AUDIT_WRITECAP_AUDIT_CONTROLCAP_SETFCAPCAP_MAC_OVERRIDECAP_MAC_ADMINCAP_SYSLOGCAP_WAKE_ALARMCAP_BLOCK_SUSPENDCAP_AUDIT_READCAP_PERFMONCAP_BPFCAP_CHECKPOINT_RESTOREevery host capability (41 on a recent kernel)Docker default00000000a80425fbCAP_CHOWNCAP_DAC_OVERRIDECAP_DAC_READ_SEARCH (out)CAP_FOWNERCAP_FSETIDCAP_KILLCAP_SETGIDCAP_SETUIDCAP_SETPCAPCAP_LINUX_IMMUTABLE (out)CAP_NET_BIND_SERVICECAP_NET_BROADCAST (out)CAP_NET_ADMIN (out)CAP_NET_RAWCAP_IPC_LOCK (out)CAP_IPC_OWNER (out)CAP_SYS_MODULE (out)CAP_SYS_RAWIO (out)CAP_SYS_CHROOTCAP_SYS_PTRACE (out)CAP_SYS_PACCT (out)CAP_SYS_ADMIN (out)CAP_SYS_BOOT (out)CAP_SYS_NICE (out)CAP_SYS_RESOURCE (out)CAP_SYS_TIME (out)CAP_SYS_TTY_CONFIG (out)CAP_MKNODCAP_LEASE (out)CAP_AUDIT_WRITECAP_AUDIT_CONTROL (out)CAP_SETFCAPCAP_MAC_OVERRIDE (out)CAP_MAC_ADMIN (out)CAP_SYSLOG (out)CAP_WAKE_ALARM (out)CAP_BLOCK_SUSPEND (out)CAP_AUDIT_READ (out)CAP_PERFMON (out)CAP_BPF (out)CAP_CHECKPOINT_RESTORE (out)14 capabilitiesofficial Postgres00000000000000cbCAP_CHOWNCAP_DAC_OVERRIDECAP_DAC_READ_SEARCH (out)CAP_FOWNERCAP_FSETID (out)CAP_KILL (out)CAP_SETGIDCAP_SETUIDCAP_SETPCAP (out)CAP_LINUX_IMMUTABLE (out)CAP_NET_BIND_SERVICE (out)CAP_NET_BROADCAST (out)CAP_NET_ADMIN (out)CAP_NET_RAW (out)CAP_IPC_LOCK (out)CAP_IPC_OWNER (out)CAP_SYS_MODULE (out)CAP_SYS_RAWIO (out)CAP_SYS_CHROOT (out)CAP_SYS_PTRACE (out)CAP_SYS_PACCT (out)CAP_SYS_ADMIN (out)CAP_SYS_BOOT (out)CAP_SYS_NICE (out)CAP_SYS_RESOURCE (out)CAP_SYS_TIME (out)CAP_SYS_TTY_CONFIG (out)CAP_MKNOD (out)CAP_LEASE (out)CAP_AUDIT_WRITE (out)CAP_AUDIT_CONTROL (out)CAP_SETFCAP (out)CAP_MAC_OVERRIDE (out)CAP_MAC_ADMIN (out)CAP_SYSLOG (out)CAP_WAKE_ALARM (out)CAP_BLOCK_SUSPEND (out)CAP_AUDIT_READ (out)CAP_PERFMON (out)CAP_BPF (out)CAP_CHECKPOINT_RESTORE (out)5, each one justifiedcap_drop: [ALL]0000000000000000CAP_CHOWN (out)CAP_DAC_OVERRIDE (out)CAP_DAC_READ_SEARCH (out)CAP_FOWNER (out)CAP_FSETID (out)CAP_KILL (out)CAP_SETGID (out)CAP_SETUID (out)CAP_SETPCAP (out)CAP_LINUX_IMMUTABLE (out)CAP_NET_BIND_SERVICE (out)CAP_NET_BROADCAST (out)CAP_NET_ADMIN (out)CAP_NET_RAW (out)CAP_IPC_LOCK (out)CAP_IPC_OWNER (out)CAP_SYS_MODULE (out)CAP_SYS_RAWIO (out)CAP_SYS_CHROOT (out)CAP_SYS_PTRACE (out)CAP_SYS_PACCT (out)CAP_SYS_ADMIN (out)CAP_SYS_BOOT (out)CAP_SYS_NICE (out)CAP_SYS_RESOURCE (out)CAP_SYS_TIME (out)CAP_SYS_TTY_CONFIG (out)CAP_MKNOD (out)CAP_LEASE (out)CAP_AUDIT_WRITE (out)CAP_AUDIT_CONTROL (out)CAP_SETFCAP (out)CAP_MAC_OVERRIDE (out)CAP_MAC_ADMIN (out)CAP_SYSLOG (out)CAP_WAKE_ALARM (out)CAP_BLOCK_SUSPEND (out)CAP_AUDIT_READ (out)CAP_PERFMON (out)CAP_BPF (out)CAP_CHECKPOINT_RESTORE (out)none↑ column 21: SYS_ADMIN, which in practice is root
Each column is a capability (bit 0 to 40). The number under the name is the CapBnd shown in /proc/1/status.

Two things help a lot here. Running as a non-root user makes the process finish execve with its effective capabilities zeroed. And the no-new-privileges flag ensures no setuid binary hands privilege back later.

Namespaces: what the process sees

A namespace gives the process its own version of a system resource: its own process list, its own network, its own hostname. Linux has eight kinds. Docker creates a new one of each for the container, except two: user and time. And the cgroup one is only new on hosts with cgroup v2; on cgroup v1 the default is to use the host's.

New for each containerpidprocessesnetnetworkmountfilesipcmemoryutshostnamecgroupv2 onlyShared with the hostuseruid 0 here = uid 0 on hosttimeclockThe most common leaks undo the greennamespaces: network_mode: host,pid: host and mounting /proc or the socket.
Without a user namespace, whoever escapes the container as root lands as root on the host.

Seccomp: which syscalls exist

Every action of a process becomes a syscall, a request to the kernel. Seccomp puts a small filter in front of each one and decides: let it through, return an error, log it or kill the process. The filter is inherited by every child process and can never be removed.

Docker's default profile denies everything by default and allows about 300 syscalls. Left out are the ones that show up in known escapes, such as mount, unshare, kexec_load, bpf and keyctl. The most important rule is simple: never turn it off (seccomp=unconfined).

Cgroups: how much it can spend

The three filters above limit what the process can do. Cgroups limit how much it can consume: number of processes (against fork bombs), memory and CPU. Without them, a bug in one container takes down every other container on the same host.

Next: the recipes, one layer at a time →

In what order to apply them

You can do it all at once, but then, when something breaks, nobody knows what it was. The order below starts with what gives the most protection per hour of work and leaves for last what breaks the most. Each step is a separate change, closed by the audit gate.

most gain per hourmore work, more breakage1baselineuser, caps,limitsgate2socket andprivilegedoutgate3namespacesand separatenetworksgate4rootfsread-only+ tmpfsgate5customseccomp(optional)gate6userns-remapon the wholedaemongate
One service at a time, one recipe per change. If something breaks, undoing it means undoing just one thing.

1. The base block

The highest-impact recipes fit in a reusable YAML snippet at the top of the compose file. Each service pulls in the block and adds only its own limits. In the image, the process runs with a numeric uid that is not 0.

# Dockerfile, final stage
USER 10001:10001

# docker-compose.yml
x-hardened: &hardened
  cap_drop: [ALL]              # bounding set empty
  security_opt:
    - no-new-privileges:true   # setuid never grants anything
  ipc: private

services:
  app:
    <<: *hardened
    pids_limit: 512            # threads count as tasks
    mem_limit: 1g
    cpus: "1.5"

Official images that start as root and switch user on their own (Postgres, Redis, nginx) need a short list back, always with a comment saying why:

Servicecap_add
Your own non-root appnone
Official PostgresCHOWN DAC_OVERRIDE FOWNER SETUID SETGID
Official RedisSETUID SETGID
Official nginx on port 80CHOWN SETUID SETGID (or nginx-unprivileged with none)

2. Docker socket and privileged

Mounting /var/run/docker.sock into a container gives it control over all of Docker. Whoever talks to the socket can create a new, privileged container with the host disk mounted. That is root on the host, and the :ro on the mount changes nothing, because it only protects the file, not the API. When a service only needs to read the container list, the way out is a proxy that allows just that read.

Without a proxystats-collectordocker.sock:roDocker daemonruns as rootcan create a privilegedcontainer with / mountedWith a socket proxystats-collectorGETPOSTsocket-proxyonly GET /containersDocker daemononly gets readsPOST → 403
The proxy has no authentication either, so it sits on a network shared only with the collector, never on the reverse proxy's network. On hosts with IPv6 turned off it needs DISABLE_IPV6=1, or it will not even start.

The same reasoning applies to privileged: true, which turns on every capability the host has and turns off seccomp. The swap is for the exact list of cap_add and devices the service documents.

3. Namespaces and separate networks

First, no network_mode: host, pid: host or ipc: host on an app service. Then, the network. On a host with several projects behind the same proxy (Dokploy does this with the dokploy-network), everything on the proxy network sees everything. The rule: only what receives traffic from the proxy joins its network, and databases stay on an internal network with no route out.

dokploy-networkthe proxy's, externalegress↑ internetbackendinternal: trueTraefik (proxy)appworkerpostgresredisanother project✕cannot reach postgres
Each dot is a service attached to a network. Databases only show up in the backend column, and the app loses its published ports as soon as the proxy starts routing it.

4. Read-only rootfs

With read_only: true, nobody can write a new binary or change the image code while the container runs. The only writable places become the ones you declare: tmpfs (gone on restart) for cache and temporary files, and volumes for what needs to last.

appuid 10001/appcode, read-only/usr /etc /binimage, read-only/tmptmpfs 128m/app/tmptmpfs 256m, uid=10001/app/storagevolume, persistentEROFS
When an EROFS shows up in the log, the fix is a tmpfs for that exact path. Never turn read-only off.
  app:
    <<: *hardened
    read_only: true
    tmpfs:
      - /tmp:size=128m,mode=1777
      - /app/tmp:size=256m,uid=10001,gid=10001,mode=0755
    volumes:
      - uploads:/app/storage

Three details that only show up when testing:

RUN mkdir -p /app/storage && chown 10001:10001 /app/storage
USER 10001:10001

And logs go to stdout, not to a folder.

5. Custom seccomp

For small, stable services (a Go or Rust binary, a job, a proxy) you can go beyond the default profile and allow only the syscalls they really use. To find out which ones, you observe first, and only then block.

1. ObserveSCMP_ACT_LOGall passes and logs2. Wait7 days, with everyscheduled task3. Counttype=1326with auditd on4. BlockSCMP_ACT_ERRNOonly the allowlistnew base image or new language version? observe again,because the runtime may start using new syscalls (such as clone3)
A profile of your own replaces the whole default. That is why it always starts from Moby's default.json, never from scratch.
Careful in step 3: without auditd, the events go to the kernel log, which is rate limited and throws most of them away. In one test, only 10 of about 580 events reached the log. Turn on auditd (and read with ausearch -m SECCOMP) or lift the limit during the window with sysctl -w kernel.printk_ratelimit=0. And keep in the allowlist the syscalls that show up with exe="/runc": runc installs the filter before starting the app, so its last steps also go through the profile.

6. User namespaces

The last step deals with the namespace Docker does not create: the user one. With userns-remap on the daemon, uid 0 inside the container becomes a high uid with no power at all on the host.

containeruid 0 … 65535host0 (root)100000 … 165535with userns-remapwithout remapcheck with cat /proc/self/uid_map inside the container
It is a change to the whole daemon and affects every project on the host: old images and volumes disappear until migrated, and on Docker 29 the remap also turns off the containerd image store and falls back to the overlay2 driver. That is why it comes last, tried first on a test host.

Next: how to prove it worked →

Prove, don't assume

Reading the compose file tells you what should be running. What counts is the state of the live container. The kernel publishes it in /proc/1/status and Docker in docker inspect. A short script joins the two into one line per container, and that line is the gate that closes each recipe: without it, the work is not done.

# scripts/hardening-audit.sh, run on the Docker host
for c in $(docker ps -q); do
  st=$(docker exec "$c" cat /proc/1/status)
  # distroless (no cat): read it from the host instead
  [ -n "$st" ] || st=$(cat /proc/$(docker inspect -f '{{.State.Pid}}' "$c")/status)
  # Uid, CapBnd, NoNewPrivs, Seccomp from the kernel,
  # ReadonlyRootfs, PidsLimit, Privileged, NetworkMode from docker inspect
done

Reading the line

Pick a container and see how each field is judged, and which recipe fixes each failure.

/myproject-app-1 uid=0 capbnd=00000000a80425fb nnp=0 seccomp=2 ro=false pids=<nil> priv=false net=myproject_default
FieldValueResultNext step
uid0FAILbaseline-service
capbnd00000000a80425fbFAILbaseline-service
nnp0FAILbaseline-service
seccomp2PASS—
rofalseFAILreadonly-rootfs
pids<nil>FAILbaseline-service
privfalsePASS—
netmyproject_defaultPASS—

5 failures. Each one points to a recipe, applied in a separate change and closed by this same gate.

What counts as PASS

FieldWhere it comes fromPASS when
uidUid: in /proc/1/statusnot 0 (your own images)
capbndCapBnd:0000000000000000 or the justified list
nnpNoNewPrivs:1
seccompSeccomp:2 (filter mode)
roHostConfig.ReadonlyRootfstrue on stateless services
pidsHostConfig.PidsLimithas a value
privHostConfig.Privilegedfalse
netHostConfig.NetworkModenot host

Negative tests

Besides reading the state, each recipe has a test that has to fail. It is the proof that the filter really is there:

  1. docker compose exec -u 0 app chown nobody /tmp fails with Operation not permitted, because not even root has a capability left.
  2. docker compose exec app touch /app/x fails with Read-only file system.
  3. docker compose exec app unshare -r true fails, because seccomp blocks creating namespaces.
  4. From inside postgres, wget -T 3 https://example.com does not get out, because the backend network has no route.
  5. From a socket proxy client, docker run alpine true gets a 403.
Golden rule: never weaken a control to make something pass. If read-only breaks a path, add a tmpfs for that path. If a capability is missing, add that capability, with a comment saying why.

← Back to the concept