Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 111 ยท Security

Securing the Docker Daemon

Why access to the Docker socket equals root on the host, how to protect the daemon with groups, TLS and SSH, why you should never mount the socket, and rootless Docker.

When you type docker run, the docker program does almost nothing itself. It sends a request to the Docker daemon (dockerd), a long-running process that usually runs as root and does the real work: pulling images, creating namespaces, mounting filesystems, starting processes. Everything in this track so far has been about making containers safer. This lesson is about the thing that creates them. If an attacker controls the daemon, every container setting you chose is irrelevant, because the attacker can simply create a new container with no limits at all.

You will learn why access to the daemon is the same as root access to the host, how the daemon is exposed (a Unix socket by default, optionally a network port), how to restrict who may talk to it, how to secure a remote daemon with TLS or SSH, and why mounting /var/run/docker.sock into a container is a decision with a very high price. All commands were run against Docker 29 on Docker Desktop, with a few clearly marked read-only examples for things that need a dedicated Linux server.

The daemon is root

The Docker client and daemon talk over an HTTP API. On Linux the daemon listens on a Unix socket, /var/run/docker.sock, which is owned by root and the group docker:

CONSOLE
$ ls -l /var/run/docker.sock
srw-rw---- 1 root docker 0 Oct 23 09:12 /var/run/docker.sock

This is a read-only example from a Linux server; Docker Desktop keeps its socket inside a VM. Anyone who can open that file can call the whole API. And the API can do this (the shape of the command is shown here, but do not run it on a machine you care about):

Terminal
# READ-ONLY EXAMPLE - this gives you a root shell on the host
docker run --rm -it -v /:/host alpine chroot /host sh

That one line starts a container as root, mounts the host's entire filesystem at /host, and changes into it. From that shell you can read /etc/shadow, add your SSH key to root's account, or install a service. No vulnerability is involved: it is the documented behavior of a feature called bind mounts. The consequence is the most important sentence in this lesson:

Being able to run docker commands is equivalent to having root on the host.

You can see the same mechanism on a harmless scale. A container that mounts a folder writes to it as the container's user, which is root unless told otherwise:

CONSOLE
$ docker run --rm -v "$PWD/out:/out" alpine:3 sh -c 'id -u; touch /out/made-by-container; ls -ln /out'
0
total 0
-rw-r--r--    1 0        0                0 Oct 23 15:08 made-by-container

The file is owned by UID 0 on the shared directory. Replace $PWD/out with /etc or /root/.ssh and you have the attack. (The folder here lives on a Windows disk, where ownership is translated by Docker Desktop; on a Linux host the file appears as owned by root in the host's directory listing.)

Treat membership of the docker group, access to the socket and access to a TCP API port as root access. Do not add colleagues to the group "to make things easier" unless you would give them sudo without a password.

How the daemon is exposed

A daemon can listen on several addresses at once. They are set with the -H flag or the hosts key in /etc/docker/daemon.json:

Address Meaning Risk
unix:///var/run/docker.sock Local socket, access controlled by file permissions Anyone in the docker group is root
fd:// Socket handed over by systemd Same as above
tcp://127.0.0.1:2375 Plain HTTP on loopback only Any local user or compromised local process is root
tcp://0.0.0.0:2375 Plain HTTP on every interface Anyone who can reach the port owns the machine
tcp://0.0.0.0:2376 with TLS HTTPS with client certificates Safe if certificates are protected
ssh://user@host (client side) The client tunnels over SSH Safe, uses SSH keys and accounts

Port 2375 without TLS is the classic mistake. Internet scanners look for it constantly, and an exposed daemon is typically found and used for cryptocurrency mining within hours. If you ever find -H tcp://0.0.0.0:2375 in a script or an old tutorial, remove it.

Limiting who can use the socket

On a Linux host the default setup is sensible: only root and the docker group can connect. Check who is in the group, and keep the list short:

CONSOLE
$ getent group docker
docker:x:998:deploy,alice

(Read-only example.) For every account on that line, ask whether it needs root on this machine. CI runners, shared build servers and bastion hosts are common places where the group grows over time.

Other ways to reduce the exposure:

  • Use a different tool for most people. Developers who only need to read container state can use a read-only proxy in front of the socket (for example a socket proxy that allows GET requests only), or a rootless daemon of their own.
  • Use sudo docker deliberately on shared hosts so that every call is logged by sudo.
  • Audit the socket. With the Linux audit system you can record who touches /var/run/docker.sock and the /var/lib/docker directory.
  • Keep live-restore and logging configured (below) so that an incident does not also destroy your evidence.

Securing a remote daemon

Sometimes you really do need to run docker against another machine. There are two good options.

Option 1: Docker over SSH

The simplest and usually best way is to let SSH carry the connection. The remote machine needs only a normal SSH account that may use Docker, and nothing new is exposed:

Terminal
docker -H ssh://[email protected] ps

Or create a named context so you do not repeat the host:

Terminal
docker context create build-server --docker "host=ssh://[email protected]"
docker --context build-server ps
docker context use build-server

(Read-only example; it needs a real server.) All the authentication, encryption and key management are SSH's. Compose supports it too: docker --context build-server compose up -d.

Option 2: TLS with client certificates

If SSH is not possible, the daemon can listen on port 2376 and demand that every client presents a certificate signed by your own certificate authority (CA). You need four things: a CA, a server certificate, a client certificate and the right daemon flags. Generating the certificates is ordinary openssl work. This is what was run (inside a throwaway Alpine container, so nothing was installed on the host) and what it printed:

CONSOLE
$ openssl genrsa -out ca-key.pem 4096
$ openssl req -new -x509 -days 30 -key ca-key.pem -sha256 -subj "/CN=Example Docker CA" -out ca.pem
$ openssl genrsa -out server-key.pem 4096
$ openssl req -new -key server-key.pem -sha256 -subj "/CN=docker.example.com" -out server.csr
$ printf 'subjectAltName = DNS:docker.example.com,IP:127.0.0.1\nextendedKeyUsage = serverAuth\n' > server-ext.cnf
$ openssl x509 -req -days 30 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
    -CAcreateserial -out server-cert.pem -extfile server-ext.cnf
Certificate request self-signature ok
subject=CN=docker.example.com
$ openssl genrsa -out key.pem 4096
$ openssl req -new -key key.pem -subj "/CN=client" -out client.csr
$ printf 'extendedKeyUsage = clientAuth\n' > client-ext.cnf
$ openssl x509 -req -days 30 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
    -CAcreateserial -out cert.pem -extfile client-ext.cnf
Certificate request self-signature ok
subject=CN=client
$ chmod 0400 ca-key.pem server-key.pem key.pem
$ chmod 0444 ca.pem server-cert.pem cert.pem
$ openssl verify -CAfile ca.pem server-cert.pem cert.pem
server-cert.pem: OK
cert.pem: OK

Three details matter. The server certificate needs a subjectAltName containing the name or IP clients will connect to, or they will refuse it. The extendedKeyUsage lines mark which certificate is for servers and which for clients. And the private keys (*-key.pem, key.pem) must be readable only by their owner; the CA key should live offline, because whoever holds it can mint certificates that give root on every daemon that trusts the CA.

Then the daemon is told to require them. This is the daemon.json for the server, as a read-only example:

JSON
{
  "hosts": ["unix:///var/run/docker.sock", "tcp://0.0.0.0:2376"],
  "tlsverify": true,
  "tlscacert": "/etc/docker/tls/ca.pem",
  "tlscert": "/etc/docker/tls/server-cert.pem",
  "tlskey": "/etc/docker/tls/server-key.pem"
}

tlsverify: true is the line that matters: it makes the daemon reject any client without a valid certificate. (On systemd hosts, remove the -H fd:// option from the service unit as well, because hosts in daemon.json conflicts with a -H flag on the command line.) The client then connects with its certificate. A context stores the paths, and Docker switches to HTTPS automatically:

CONSOLE
$ docker context create secure-remote --docker "host=tcp://docker.example.com:2376,ca=ca.pem,cert=cert.pem,key=key.pem"
secure-remote
Successfully created context "secure-remote"
$ docker context ls --format '{{.Name}} {{.DockerEndpoint}}'
default npipe:////./pipe/docker_engine
desktop-linux npipe:////./pipe/dockerDesktopLinuxEngine
secure-remote tcp://docker.example.com:2376

(Run here with 127.0.0.1:18222 as the host; the default and desktop-linux lines are the Docker Desktop contexts on this Windows machine.) With nothing listening, the failure shows that the client really uses HTTPS:

CONSOLE
$ docker --context secure-remote version
error during connect: Get "https://127.0.0.1:18222/v1.56/version": dial tcp 127.0.0.1:18222: connectex: No connection could be made because the target machine actively refused it.

Note https:// in the URL: a context with TLS files always speaks TLS. Without ca, cert and key, the same tcp:// host would be plain HTTP.

Never mount the socket into a container

Many tools ask you to run them with -v /var/run/docker.sock:/var/run/docker.sock: CI agents, dashboards, reverse proxies that discover containers, update tools. Each convenience works by giving the container the full Docker API, which means root on the host. If the application inside has a bug, such as a remote-code-execution flaw in a web dashboard, the attacker gets the host.

Mounting the socket read-only (:ro) does not help. The ro flag protects the socket file from being deleted or changed, but you can still send any API request through it.

When you are tempted to mount the socket, work through these alternatives:

Need Safer approach
Build images in CI Rootless BuildKit, buildx with a remote builder, or a managed build service (see Docker in CI)
Run containers from a test (Testcontainers) A dedicated, disposable VM or runner; see Docker in Docker and Socket Access
Reverse proxy that discovers services A socket proxy that exposes only the GET /containers/json and events endpoints, or a static configuration
Monitoring Agents that read cgroups, or a proxy limited to read-only endpoints
Manual administration A client connecting over SSH or TLS from outside

If you truly must, keep the container short-lived, never expose it to the internet, run it in a network with no other services, and keep it patched. Treat the host as having the same trust level as that container.

Hardening options in daemon.json

The daemon has settings that raise the baseline for every container it starts. The file is /etc/docker/daemon.json on Linux, and a restart applies it. These are the ones worth knowing (a read-only example; do not paste it unchanged):

JSON
{
  "live-restore": true,
  "no-new-privileges": true,
  "userland-proxy": false,
  "icc": false,
  "log-driver": "json-file",
  "log-opts": { "max-size": "10m", "max-file": "3" },
  "default-ulimits": { "nofile": { "Name": "nofile", "Soft": 64000, "Hard": 64000 } }
}
  • live-restore keeps containers running while the daemon restarts, so patching dockerd does not cause an outage. It is off by default, as you can verify:

    CONSOLE
    $ docker info --format 'live={{.LiveRestoreEnabled}} root={{.DockerRootDir}}'
    live=false root=/var/lib/docker
    
  • no-new-privileges makes that flag the default for every container.

  • icc: false disables container-to-container traffic on the default bridge network. User-defined networks (User-Defined Bridge Networks) are unaffected, so this only closes a legacy hole.

  • log-opts caps log files; without it a chatty container can fill the disk.

  • userns-remap maps container root to an unprivileged host user (see seccomp, AppArmor and Read-Only Filesystems).

Also protect the data: /var/lib/docker contains every image layer, volume and container filesystem, so it must be readable by root only, on an encrypted disk if the host holds sensitive data.

Rootless Docker

The cleanest way to stop "daemon access means root" is to not run the daemon as root. In rootless mode both the daemon and the containers run as an ordinary user, using user namespaces. The socket lives in the user's runtime directory, and there is nothing to escalate to:

CONSOLE
$ dockerd-rootless-setuptool.sh install
$ export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock
$ docker info --format '{{json .SecurityOptions}}'
["name=seccomp,profile=builtin","name=rootless","name=cgroupns"]

(Read-only example; it needs a Linux host with newuidmap.) The name=rootless entry confirms the mode. A container escape now lands as the user, who has no more rights than they did before. The trade-offs are real: you cannot bind ports below 1024 by default, networking goes through a user-space stack and is slower, --privileged does little, and a few storage and network drivers are unavailable. For developer workstations, CI runners and any service that runs code you do not control, the trade is usually worth it.

A related project is rootless Podman and other daemon-less runtimes, which avoid the central privileged process altogether. If your platform lets you choose, that is a legitimate alternative.

A short checklist for the daemon

  1. The socket is reachable only by root and a short docker group, and nothing listens on plain TCP.
  2. Remote access uses SSH or mutual TLS (tlsverify), with the CA key kept offline.
  3. No container mounts /var/run/docker.sock unless the risk is accepted in writing.
  4. live-restore, log rotation and no-new-privileges are set in daemon.json.
  5. Docker and the kernel are patched, because a daemon bug or a kernel bug skips every other layer.
  6. Where possible, run rootless.

The complete list for build, ship and run is in A Container Security Checklist.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is membership of the docker group effectively the same as root on the host?

    Anyone who can use the API can run a container with -v /:/host, which gives a root-level view and control of the host through a normal, documented feature.
  2. 2. Which daemon address is the most dangerous?

    Port 2375 without TLS serves the full API over plain HTTP to anyone who can reach it. Scanners find these within hours.
  3. 3. A tool asks you to mount /var/run/docker.sock into its container. Does adding :ro make that safe?

    Read-only on a socket file does not restrict what you send through it. The API call to create a container still goes through.
  4. 4. What does tlsverify: true do in daemon.json?

    With tlsverify the daemon requires mutual TLS: clients must present a certificate signed by the CA in tlscacert.
  5. 5. What is the main security benefit of rootless Docker?

    Both the daemon and the containers run as an ordinary user, so breaking out does not give root privileges on the host.

Summary

  • The Docker daemon runs as root; anyone who can use its socket or API can get a root shell on the host. Treat the docker group like sudo without a password.
  • Never expose tcp://...:2375 without TLS. Remote access should use ssh:// contexts or tlsverify with client certificates; keep the CA key offline.
  • A server certificate needs a subjectAltName; client and server certificates carry different extendedKeyUsage values.
  • Do not mount /var/run/docker.sock into containers; :ro does not make it safe. Use rootless builders, socket proxies or dedicated runners instead.
  • Set live-restore, log rotation and no-new-privileges in daemon.json, and keep /var/lib/docker private.
  • Rootless mode removes the root daemon entirely and is the strongest option for workstations and CI.

Next: A Container Security Checklist