basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Hardening containers in Compose: cap_drop, read_only, no-new-privileges, and limits

    By default Docker grants every container 14 kernel capabilities, a writable root filesystem, and access to all host memory and PIDs. Five blocks in compose.yaml — cap_drop: [ALL], no-new-privileges, read_only with tmpfs, plus memory, CPU, and PID limits — close those gaps without rebuilding the image.

    What a container can do by default

    An unrestricted container in compose.yaml gets far more from Docker than a web service needs. If someone exploits a bug in the app, the process inside can write into its own container layer, use 14 default kernel capabilities (NET_RAW, CHOWN, DAC_OVERRIDE, SETUID, and others), invoke setuid binaries, and consume all host RAM and PID table entries — letting the OOM killer take down neighboring containers and sshd.

    Risk closed In compose.yaml What remains
    Extra root privileges cap_drop: [ALL] plus cap_add if needed only capabilities required to start (or none)
    Privilege escalation via setuid/setgid security_opt: [no-new-privileges:true] the process can’t gain more privileges than it started with
    Tampering with image files read_only: true and tmpfs writes go only to mounted volumes and in-memory temp dirs
    Exhausting RAM, CPU, or PIDs mem_limit, memswap_limit, cpus, pids_limit a leak or runaway loop hits only this container

    These settings work in standard Docker Engine and require no image rebuild. They don’t replace daemon-level user isolation (rootless or userns-remap), but they cut out most of the attack surface in every stack.

    Setup

    1. Drop all capabilities and block privilege escalation

      Add to the service definition:

      cap_drop: [ALL]
      security_opt:
        - no-new-privileges:true

      Start here for every container. An app that already runs as non-root and listens above port 1024 (such as a Node.js or Go service on port 3000) works with this block and zero cap_add entries — no kernel capabilities at all.

      If a container fails at startup with Operation not permitted or Permission denied, add back only what its entrypoint needs:

      • nginx on port 80 (master starts as root to bind port 80, then drops workers to the nginx user): cap_add: [CHOWN, SETGID, SETUID, NET_BIND_SERVICE].
      • official postgres:16-alpine (entrypoint runs chmod 700 on the data directory, traverses it, and switches to the postgres user via su-exec): cap_add: [CHOWN, DAC_OVERRIDE, DAC_READ_SEARCH, FOWNER, SETGID, SETUID].
    2. Mount the root filesystem read_only and move temp dirs to tmpfs

      read_only: true
      tmpfs:
        - /var/cache/nginx
        - /run
        - /tmp

      With read_only: true, the image filesystem is read-only: nothing inside can modify configs, templates, or binaries. Writes go only to mounted volumes (volumes:) and tmpfs directories, which live in RAM and clear on restart.

      To see where an unfamiliar image writes, start it once without read_only and run docker diff <container> (Everyday Docker): add every A and C path outside volumes to tmpfs. Not every image supports read_only out of the box (for instance, an app that caches files inside /app right beside its code): in that case, keep cap_drop, no-new-privileges, and resource limits, and turn on read_only wherever write paths are cleanly separated.

    3. Set memory, CPU, and PID limits

      mem_limit: 64M
      memswap_limit: 96M
      cpus: 0.5
      pids_limit: 100
      • mem_limit caps container RAM: on a leak, the kernel kills only this container (OOMKilled: true) while neighboring services stay up.
      • memswap_limit is combined RAM plus swap (64M RAM + 32M swap = 96M); setting it equal to mem_limit disables swap for the container.
      • cpus caps CPU share (0.5 = half of one core) so a stuck loop can’t lock up the host.
      • pids_limit caps processes and threads inside the container, blocking fork bombs and thread leaks.

      Baseline numbers to start from and tune against docker stats --no-stream:

      • static nginx: mem_limit: 64M, memswap_limit: 96M, pids_limit: 100;
      • PostgreSQL for a small service: mem_limit: 256M, memswap_limit: 384M, pids_limit: 100;
      • Node.js / Next.js app: mem_limit: 384M, memswap_limit: 512M, pids_limit: 150.
    4. Put together the final compose.yaml

      Static site on nginx — read_only: true, tmpfs, and four capabilities:

      services:
        web:
          image: nginx:1.31.8-alpine
          mem_limit: 64M
          memswap_limit: 96M
          cpus: 0.5
          pids_limit: 100
          read_only: true
          tmpfs:
            - /var/cache/nginx
            - /run
            - /tmp
          cap_drop: [ALL]
          cap_add: [CHOWN, SETGID, SETUID, NET_BIND_SERVICE]
          security_opt:
            - no-new-privileges:true
          restart: unless-stopped

      Web app (zero capabilities) and PostgreSQL on an isolated internal network (Docker networks):

      services:
        app:
          image: ghcr.io/example-user/app:1.0
          mem_limit: 384M
          memswap_limit: 512M
          cpus: 0.5
          pids_limit: 150
          cap_drop: [ALL]
          security_opt:
            - no-new-privileges:true
          restart: unless-stopped
          networks:
            - proxy
            - internal
      
        db:
          image: postgres:16-alpine
          mem_limit: 256M
          memswap_limit: 384M
          cpus: 0.5
          pids_limit: 100
          cap_drop: [ALL]
          cap_add: [CHOWN, DAC_OVERRIDE, DAC_READ_SEARCH, FOWNER, SETGID, SETUID]
          security_opt:
            - no-new-privileges:true
          volumes:
            - db_data:/var/lib/postgresql/data
          restart: unless-stopped
          networks:
            - internal
      
      networks:
        proxy:
          external: true
        internal:
          internal: true
      
      volumes:
        db_data:
    5. Apply and check startup logs

      cd /opt/site && docker compose up -d
      docker compose ps
      docker compose logs --tail 30

      If a container enters Restarting, the first log lines show which cap_add capability or tmpfs mount is missing.

    If it doesn’t work

    nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system) or failure writing /run/nginx.pid

    Cause
    read_only: true is on, and a directory where the service writes temporary files isn’t mounted on tmpfs.
    Fix
    Grab the path from docker logs, add it to tmpfs:, and recreate the container (docker compose up -d). For nginx, that’s /var/cache/nginx, /run, and /tmp.

    nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied) or setgid(101) failed (1: Operation not permitted)

    Cause
    cap_drop: [ALL] removed the capability to bind ports below 1024 (NET_BIND_SERVICE) or switch users (SETUID, SETGID, CHOWN).
    Fix
    Add back only the needed capabilities in cap_add — for nginx on port 80, [CHOWN, SETGID, SETUID, NET_BIND_SERVICE]. If you switch the image to a port above 1024 and a non-root user, cap_add isn’t needed.

    PostgreSQL won’t start: chmod: /var/lib/postgresql/data: Operation not permitted or su-exec: setgroups: Operation not permitted

    Cause
    The official postgres entrypoint starts as root, sets mode 700 on PGDATA, and drops to the postgres user via su-exec.
    Fix
    Add [CHOWN, DAC_OVERRIDE, DAC_READ_SEARCH, FOWNER, SETGID, SETUID] to cap_add.

    Container crashes under load; docker inspect shows OOMKilled: true and ExitCode: 137

    Cause
    mem_limit sits below the app’s working set — for instance, a Node.js server holds 200–250 MB steadily and spikes above that.
    Fix
    Check actual usage with docker stats --no-stream (Everyday Docker) and raise mem_limit with headroom, keeping memswap_limit above mem_limit.

    Service stops responding or crashes with fork: Resource temporarily unavailable

    Cause
    pids_limit kicked in: the application spawns more threads than the cap allows.
    Fix
    Check current process and thread counts in the PIDS column of docker stats --no-stream and set pids_limit to roughly double that.

    docker compose up -d fails with an error about memswap_limit and mem_limit

    Cause
    memswap_limit sets combined RAM + swap, not swap alone, so it can’t be lower than mem_limit.
    Fix
    Set memswap_limit greater than or equal to mem_limit: mem_limit: 256M with memswap_limit: 384M gives 128 MB of swap; equal values turn swap off for the container.

    How to check

    Inspect the applied settings with docker inspect:

    docker inspect web --format 'Readonly={{.HostConfig.ReadonlyRootfs}} CapDrop={{.HostConfig.CapDrop}} CapAdd={{.HostConfig.CapAdd}} SecOpt={{.HostConfig.SecurityOpt}} Mem={{.HostConfig.Memory}} Pids={{.HostConfig.PidsLimit}}'
    # Readonly=true CapDrop=[ALL] CapAdd=[CHOWN SETGID SETUID NET_BIND_SERVICE] SecOpt=[no-new-privileges:true] Mem=67108864 Pids=100

    Test that root filesystem writes are blocked while tmpfs stays writable:

    docker exec web touch /etc/test-ro
    # touch: /etc/test-ro: Read-only file system
    
    docker exec web touch /tmp/test-rw && docker exec web rm /tmp/test-rw

    For an app without cap_add, the effective capability mask in /proc/1/status is all zeroes (just like verifying a systemd sandbox in systemd sandbox):

    docker exec app grep CapEff /proc/1/status
    # CapEff:	0000000000000000