TExcelTAD
Home › Docker Compose › Compose Security

Compose Security

A compose file is a security document. It decides which ports are reachable from the internet, which user processes run as, what they may do to the kernel, which secrets they see and whether one compromised container can take over the host. Most defaults are reasonable for development and too generous for production. This lesson goes through the settings that matter, roughly in order of impact. For the image side (minimal base images, scanning, non-root USER in the Dockerfile), see Docker Security.

1. Exposure: what can be reached?

The most common real-world incident is not an exotic container escape; it's a database published to the internet with a weak password.

  • ports: ["5432:5432"] binds to all interfaces (0.0.0.0). On a server with a public IP, that's the internet. Docker also inserts its own firewall rules, so ufw deny 5432 does not protect a published port.
  • Publish only the reverse proxy. Everything else talks over the project network by service name.
  • Need a port for local tools? Bind it to localhost: "127.0.0.1:5432:5432".
  • Databases and caches go on an internal: true network (see Networks).

2. Privileges: what can a process do?

compose · try it yourself
services:
  api:
    image: ghcr.io/acme/api@sha256:4f9a3c1d2b7e8f60a1b2c3d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5a6b7c
    user: "10001:10001"
    read_only: true
    tmpfs: ["/tmp:size=16m"]
    cap_drop: [ALL]
    cap_add: [NET_BIND_SERVICE]
    security_opt: ["no-new-privileges:true"]
    privileged: false
    pids_limit: 100
    ulimits:
      nofile: {soft: 4096, hard: 8192}
    ports: ["127.0.0.1:8080:8080"]
name: demo
services:
  api:
    cap_add:
      - NET_BIND_SERVICE
    cap_drop:
      - ALL
    image: ghcr.io/acme/api@sha256:4f9a3c1d2b7e8f60a1b2c3d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5a6b7c
    networks:
      default: null
    pids_limit: 100
    read_only: true
    security_opt:
      - no-new-privileges:true
    tmpfs:
      - /tmp:size=16m
    ulimits:
      nofile:
        soft: 4096
        hard: 8192
    user: 10001:10001
    ports:
      - mode: ingress
        host_ip: 127.0.0.1
        target: 8080
        published: "8080"
        protocol: tcp
networks:
  default:
    name: demo_default
Setting Protects against
image: …@sha256:… a tag being re-pointed to a different (malicious or broken) image
user: "10001:10001" root inside the container = root-owned files, easier escapes; run as an unprivileged UID
read_only: true + tmpfs attackers writing tools or persistence into the filesystem
cap_drop: [ALL] + minimal cap_add kernel capabilities the app never needs (raw sockets, chown, mount…)
no-new-privileges setuid binaries (like su) gaining root inside the container
pids_limit, ulimits fork bombs, file-descriptor exhaustion

privileged: false is the default, which is why Compose doesn't even print it. The dangerous direction is privileged: true: it gives the container every capability and access to all host devices, which is effectively root on the host. Keep it out of application services entirely.

3. The Docker socket

Mounting /var/run/docker.sock lets a container start other containers, including one that mounts the host's / with privileged: true. Whoever controls that container controls the host. :ro doesn't help: it makes the socket file read-only, not the API behind it. Tools that need it (Traefik, Portainer, CI runners, Watchtower) should be trusted, kept up to date, and ideally use a socket proxy that only allows the API calls they need (for example read-only container listing).

4. Secrets

  • Use secrets mounted as files, not environment variables, for anything sensitive.
  • Never commit .env files with real values. Commit an .env.example with placeholders.
  • docker compose config prints interpolated values. That's useful, and dangerous if you paste its output into a ticket or CI log:
compose · try it yourself
services:
  api:
    image: ghcr.io/acme/api:3.1
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/app
    secrets: [stripe_key]
secrets:
  stripe_key:
    environment: STRIPE_KEY

# --- .env
DB_PASSWORD=hunter2-not-for-logs
STRIPE_KEY=sk_live_never_printed
name: demo
services:
  api:
    environment:
      DATABASE_URL: postgres://app:hunter2-not-for-logs@db:5432/app
    image: ghcr.io/acme/api:3.1
    networks:
      default: null
    secrets:
      - source: stripe_key
        target: /run/secrets/stripe_key
networks:
  default:
    name: demo_default
secrets:
  stripe_key:
    name: demo_stripe_key
    environment: STRIPE_KEY

The password interpolated into DATABASE_URL appears in plain text, while the secret only shows where its value comes from. Two more reasons to prefer secrets: docker inspect shows environment variables to anyone who can talk to the daemon, and so does any crash reporter that dumps the environment.

5. Images and supply chain

  • Pin versions (postgres:17.6) or digests, and update deliberately (Renovate/Dependabot can bump compose files).
  • Prefer official or verified images and small bases (Alpine, distroless, -slim).
  • Scan images in CI (docker scout cves, Trivy, Grype) and fail on critical issues.
  • Build with no secrets in layers: use BuildKit secret mounts (build.secrets in Compose), never ARG PASSWORD.

A tiny compose auditor

A few of these rules as code. Run it against your own files (it uses PyYAML on the compose text):

python · try it yourself
import yaml

COMPOSE = """
services:
  proxy:
    image: caddy:2.10
    ports: ["80:80", "443:443"]
  api:
    image: ghcr.io/acme/api:latest
    environment:
      DB_PASSWORD: hunter2
    volumes: ["/var/run/docker.sock:/var/run/docker.sock:ro"]
  db:
    image: postgres:17
    ports: ["5432:5432"]
  admin:
    image: ghcr.io/acme/admin:1.4.2
    privileged: true
    user: root
"""

SENSITIVE = ("PASSWORD", "SECRET", "TOKEN", "KEY")

def audit(name, svc):
    issues = []
    image = svc.get("image", "")
    if "@sha256:" not in image and (":" not in image or image.endswith(":latest")):
        issues.append("image uses 'latest' or no tag")
    for p in svc.get("ports", []):
        if name != "proxy" and not str(p).startswith("127.0.0.1:"):
            issues.append(f"port {p} published on all interfaces")
    for v in svc.get("volumes", []):
        if "docker.sock" in v:
            issues.append("mounts the Docker socket (host root)")
    if svc.get("privileged"):
        issues.append("privileged: true")
    if str(svc.get("user", "")) in ("root", "0", "0:0"):
        issues.append("runs as root explicitly")
    for k in svc.get("environment", {}):
        if any(s in k.upper() for s in SENSITIVE):
            issues.append(f"secret-looking variable {k} in environment")
    if "cap_drop" not in svc:
        issues.append("no cap_drop (info)")
    return issues

for name, svc in yaml.safe_load(COMPOSE)["services"].items():
    found = audit(name, svc)
    print(f"{name}: {'ok' if not found else ''}")
    for issue in found:
        print(f"  - {issue}")
proxy:
  - no cap_drop (info)
api:
  - image uses 'latest' or no tag
  - mounts the Docker socket (host root)
  - secret-looking variable DB_PASSWORD in environment
  - no cap_drop (info)
db:
  - port 5432:5432 published on all interfaces
  - no cap_drop (info)
admin:
  - privileged: true
  - runs as root explicitly
  - no cap_drop (info)

Real tools go further (Checkov, KICS and Trivy's config scanner all understand compose files), but even a check like this in CI catches the classic mistakes.

6. The daemon itself

Everything above limits what a container can do through the Docker daemon, which itself runs as root. Two host-level options reduce that further: rootless Docker (the daemon runs as an unprivileged user) and user namespace remapping (userns-remap: root in the container maps to an unprivileged UID on the host). Both have trade-offs (some networking and storage features are limited), but they turn a container escape into an unprivileged-user compromise. And remember: membership in the docker group is equivalent to root on that machine.

Security checklist

text
[ ] only the proxy publishes ports; dev ports bound to 127.0.0.1
[ ] databases on internal networks
[ ] every service: non-root user, cap_drop ALL, no-new-privileges
[ ] read_only root filesystem where possible, small tmpfs for scratch
[ ] memory + pids limits
[ ] secrets as files; .env not in Git; config output treated as sensitive
[ ] images pinned (tag or digest) and scanned in CI
[ ] no privileged, no docker.sock (or a filtered socket proxy)

Learn more: Docker Security · Configs & Secrets · Swarm Security · Kubernetes Security Contexts

Test yourself

A server's firewall (ufw) denies port 5432, but compose publishes "5432:5432". Is the database reachable from outside?

  1. No, ufw blocks it
  2. Yes, likely: Docker adds its own iptables rules for published ports, bypassing ufw's rules
  3. Only over IPv6
  4. Only from other containers

Why is mounting /var/run/docker.sock read-only (:ro) not a real protection?

  1. It is a real protection
  2. ro only affects the socket file, not the Docker API calls made through it
  3. Docker ignores :ro
  4. Because the socket is a directory

Which pair makes a container's root filesystem immutable while still allowing temp files?

  1. privileged + tmpfs
  2. read_only: true + tmpfs for /tmp
  3. cap_drop ALL + user root
  4. no-new-privileges + volumes