Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 111 ยท Security

seccomp, AppArmor and Read-Only Filesystems

Lock down containers with seccomp profiles, AppArmor, read-only root filesystems, tmpfs and user namespaces. Real commands, real output and a hardened Compose file.

Dropping capabilities and running as a non-root user shrink what a process is allowed to do. This lesson adds three more layers that shrink what an attacker can reach if a process is compromised anyway: a system call filter (seccomp), a mandatory access control profile (AppArmor, or SELinux on other distributions), and a read-only filesystem so nothing can be planted or modified. At the end you will also meet user namespaces and rootless mode, which change what "root inside the container" means on the host.

None of these layers is exotic. Docker already applies two of them to every container you start. The skill is knowing what they do, how to see them working, and which one to turn up for a given service. All output below comes from a real Docker 29 on Docker Desktop (a Linux VM); the commands behave the same on a Linux server unless a note says otherwise.

The layers at a glance

TEXT
 process in a container
        |
        |  1. namespaces        what it can SEE      (PIDs, mounts, network)
        |  2. capabilities      what root may DO
        |  3. seccomp           which SYSTEM CALLS it may make
        |  4. AppArmor/SELinux  which FILES and OPERATIONS a profile allows
        |  5. read-only rootfs  whether it can WRITE to the image filesystem
        v
      Linux kernel (shared by every container)

Each layer is checked independently. An attack must get past all of them, which is the whole point of defense in depth. If you have not read Container Security Basics and Non-Root Users and Capabilities yet, start there.

seccomp: filtering system calls

Every action a program takes against the kernel, such as opening a file, creating a socket or starting a process, is a system call. Linux has more than 300 of them. A normal web server uses a few dozen. seccomp (secure computing mode) lets a process install a filter that decides, call by call, whether the kernel should run it, refuse it with an error, or kill the process.

Docker ships a default seccomp profile and applies it to every container unless you say otherwise. It blocks a few dozen of the 300+ calls, mostly ones that are dangerous or that normal applications never need (loading kernel modules, changing the clock, rebooting, tracing other processes, and others). You can see whether the filter is active from inside the container:

CONSOLE
$ docker run --rm alpine:3 grep -E 'Seccomp|NoNewPrivs' /proc/self/status
NoNewPrivs:	0
Seccomp:	2
Seccomp_filters:	2

Seccomp: 2 means "filter mode": a filter is installed. (0 would mean no filter at all.) The Seccomp_filters line counts how many filters are stacked; on Docker Desktop one extra filter is always present in the environment, so your number can differ by one from a plain Linux host.

Seeing the default profile block something

The default profile is subtle because it uses conditions: some calls are only allowed when the container has a given capability. Creating a new user namespace is a good example. It is blocked unless the container holds CAP_SYS_ADMIN:

CONSOLE
$ docker run --rm alpine:3 unshare -U true
unshare: unshare(0x10000000): Operation not permitted
$ echo $?
1

unshare -U asks for a new user namespace. That feature has a history of kernel bugs, so Docker refuses it by default. Turning seccomp off for one run shows that the profile, not the filesystem or the capabilities, was responsible:

CONSOLE
$ docker run --rm --security-opt seccomp=unconfined alpine:3 unshare -U true
$ echo $?
0

--security-opt seccomp=unconfined removes Docker's profile entirely. It is a debugging tool ("does this error go away without seccomp?"), not a fix. If an application needs one extra system call, write a profile that adds exactly that call (below) instead of disabling the whole filter.

Writing your own profile

A seccomp profile is a JSON file. Three fields matter: defaultAction (what happens to calls you do not mention), a list of syscalls entries, each with names and an action, and optionally errnoRet (which error number the program sees). This tiny profile allows everything except creating directories, so you can watch the filter work:

JSON
{
  "defaultAction": "SCMP_ACT_ALLOW",
  "syscalls": [
    {
      "names": ["mkdir", "mkdirat"],
      "action": "SCMP_ACT_ERRNO",
      "errnoRet": 1
    }
  ]
}

Save it as no-mkdir.json and pass the path with --security-opt. The Docker CLI reads the file on your machine and sends its content to the daemon, so the path is relative to where you run the command:

CONSOLE
$ docker run --rm --security-opt seccomp=no-mkdir.json alpine:3 sh -c 'mkdir /tmp/x; touch /tmp/ok && echo touch works'
mkdir: can't create directory '/tmp/x': Operation not permitted
touch works
$ docker run --rm alpine:3 sh -c 'mkdir /tmp/x && echo mkdir works'
mkdir works

errnoRet: 1 is the number for "Operation not permitted" (EPERM), which is why the message reads that way. A typo in the path fails before the container even starts:

CONSOLE
$ docker run --rm --security-opt seccomp=nonexist.json alpine:3 true
docker: opening seccomp profile (nonexist.json) failed: open nonexist.json: The system cannot find the file specified.

(The last words come from the Windows host used for this session; on Linux you will see "no such file or directory".)

The main actions you will use:

Action Effect
SCMP_ACT_ALLOW The call runs normally
SCMP_ACT_ERRNO The call fails with the error in errnoRet; the program keeps running
SCMP_ACT_KILL_PROCESS The kernel kills the whole process
SCMP_ACT_LOG The call runs, but the kernel logs it (useful when drafting a profile)

An allow-list is safer than a block-list

The example above is a block-list: allow everything, deny a few things. Security-minded teams go the other way. They start from "defaultAction": "SCMP_ACT_ERRNO" and list only the calls the application is known to need. That is much stronger, but also much more work: a single missing call makes the app fail in a confusing way. The practical workflow is:

  1. Start from Docker's default profile (it is published in the Moby source code) and copy it.
  2. Run your app with SCMP_ACT_LOG as the default action while you exercise every feature, collecting the calls it makes (tools such as strace and the kernel audit log help).
  3. Turn that list into an allow-list, test again, and keep the profile in version control next to the Dockerfile.

For most teams the best return is not writing profiles. Keep Docker's default profile on (never use unconfined in production), add no-new-privileges and a read-only filesystem, and spend the saved effort on dropping capabilities and patching images.

AppArmor and SELinux: access control by profile

seccomp decides which system calls a process can make. A Linux Security Module (LSM) decides which resources it may touch with them. Docker integrates with two:

  • AppArmor, the default on Debian, Ubuntu and SUSE. Docker generates a profile called docker-default and attaches it to each container. It denies things like writing to /proc/sys, mounting filesystems, and accessing raw kernel memory.
  • SELinux, the default on Fedora, RHEL and derivatives. With --security-opt label=... and the daemon's --selinux-enabled option, containers run under the container_t type, and mounted volumes can be relabeled with the :z and :Z volume suffixes.

On a Docker host with AppArmor you can check what the daemon offers, and pick a profile per container:

CONSOLE
$ docker info --format '{{json .SecurityOptions}}'
["name=apparmor","name=seccomp,profile=builtin","name=cgroupns"]
$ docker run --rm --security-opt apparmor=docker-default alpine:3 cat /proc/self/attr/current
docker-default (enforce)

This is a read-only example from a typical Ubuntu server. The Docker Desktop VM used to verify this lesson ships without AppArmor, so it prints only the last two entries of the list:

CONSOLE
$ docker info --format '{{json .SecurityOptions}}'
["name=seccomp,profile=builtin","name=cgroupns"]

Your own profile is a text file loaded into the kernel with apparmor_parser -r -W myprofile and then used with --security-opt apparmor=myprofile. Writing AppArmor or SELinux policies is a specialist job; in practice the default profile does a lot of work and you only need to know that:

  • it exists, and you should not disable it (apparmor=unconfined, label=disable) without a documented reason;
  • a "Permission denied" that survives --privileged-style debugging may come from an LSM, so look at the host's audit log (dmesg, journalctl -k, or /var/log/audit/audit.log);
  • --privileged turns these protections off, which is one more reason to avoid it.

Read-only root filesystems

An image is a stack of read-only layers with a thin writable layer on top (see Container Storage). By default a process can write anywhere in that top layer: install a tool, replace a script, drop a web shell. The --read-only flag mounts the whole container filesystem read-only:

CONSOLE
$ docker run --rm --read-only alpine:3 sh -c 'touch /x'
touch: /x: Read-only file system
$ docker run --rm --read-only alpine:3 sh -c 'echo hi > /tmp/x'
sh: can't create /tmp/x: Read-only file system

Volumes and bind mounts you add are not affected, so a database can still write its data directory. Everything else, including /tmp, is locked. That is a strong defense: an attacker who gets code execution cannot persist a modified binary or config file, and many exploit chains that need to write a payload simply fail.

Giving applications the writable spots they need

Real programs write temporary files, pid files and caches. If you simply add --read-only, they often crash. The nginx image is a typical case:

CONSOLE
$ docker run -d --name web --read-only nginx:alpine
$ docker ps -a --filter name=web --format '{{.Status}}'
Exited (1) 3 seconds ago
$ docker logs web 2>&1 | tail -2
2026/10/23 15:04:51 [emerg] 1#1: mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system)
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system)

The error message tells you exactly which path needs to be writable. Mount a tmpfs (an in-memory filesystem) there. Nothing touches the image layers, and the data disappears with the container:

CONSOLE
$ docker run -d --name web --read-only \
    --tmpfs /var/cache/nginx --tmpfs /var/run --tmpfs /tmp nginx:alpine
$ docker ps --filter name=web --format '{{.Status}}'
Up 4 seconds
$ docker diff web
$

docker diff lists every change made to the container's writable layer. It is empty, which is the proof you want: the container is running and has written nothing to its filesystem. If docker diff shows files, they are your list of what still needs a tmpfs or a volume. See tmpfs and In-Memory Storage for sizes and options.

A tmpfs mount can carry extra hardening flags. The noexec option forbids running anything stored there, which blocks the classic "download a payload to /tmp and run it" attack. Docker applies noexec, nosuid and nodev to a bare --tmpfs by default, and you can set a size cap:

CONSOLE
$ docker run --rm --read-only --tmpfs /tmp:rw,noexec,nosuid,size=16m alpine:3 \
    sh -c 'mount | grep " /tmp "; cp /bin/true /tmp/t; /tmp/t; echo "exit $?"'
tmpfs on /tmp type tmpfs (rw,nosuid,nodev,noexec,relatime,size=16384k)
sh: /tmp/t: Permission denied
exit 126

The copy succeeded, but running it was refused. Be aware that some software legitimately executes from temp directories (JIT compilers, some Java and Node tooling), so test before you ship noexec.

A good loop for hardening an existing service: run it with --read-only and no tmpfs, read the first "Read-only file system" error, add that path as tmpfs, repeat. Usually two or three paths are enough. Then confirm with docker diff that the layer stays clean.

Putting it together in Compose

All of these options have Compose equivalents. This file runs nginx with a read-only root filesystem, a short capability list, no-new-privileges, and publishes only on the loopback address:

YAML
name: hardened
services:
  web:
    image: nginx:alpine
    read_only: true
    tmpfs:
      - /var/cache/nginx
      - /var/run
      - /tmp
    cap_drop: [ALL]
    cap_add: [CHOWN, SETGID, SETUID, NET_BIND_SERVICE]
    security_opt:
      - no-new-privileges:true
      # - seccomp=./profiles/web-seccomp.json
      # - apparmor=docker-default
    ports:
      - "127.0.0.1:8080:80"

Starting it and checking that every setting really arrived:

CONSOLE
$ docker compose up -d
 Network hardened_default Created
 Container hardened-web-1 Created
 Container hardened-web-1 Started
$ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/
200
$ docker inspect hardened-web-1 --format '{{.HostConfig.ReadonlyRootfs}} {{.HostConfig.SecurityOpt}} {{.HostConfig.CapDrop}} {{.HostConfig.CapAdd}}'
true [no-new-privileges:true] [ALL] [CAP_CHOWN CAP_NET_BIND_SERVICE CAP_SETGID CAP_SETUID]
$ docker exec hardened-web-1 touch /etc/x
touch: /etc/x: Read-only file system
$ docker exec hardened-web-1 grep -E 'NoNewPrivs|CapEff' /proc/1/status
CapEff:	00000000000004c1
NoNewPrivs:	1

NoNewPrivs: 1 confirms that no process inside can gain privileges through setuid binaries, and CapEff (a bit mask) shows only four capabilities remain, compared with the default fourteen. Notice that the server still answers with 200: hardening should not change behavior. The commented lines show where a custom seccomp or AppArmor profile would go.

User namespaces and rootless mode

All of the above leaves one uncomfortable fact: by default, UID 0 inside a container is UID 0 on the host. Namespaces and capabilities limit what that root can do, but if something breaks out, it breaks out as the real root. Two features change that.

User namespace remapping (userns-remap in the daemon configuration) maps container UIDs to an unprivileged range on the host. Root in the container becomes, for example, UID 100000 outside. A breakout then lands as a user with no special rights. The price is compatibility: remapping is a daemon-wide setting, images and volumes get a separate storage area per mapping, and options such as --privileged, --pid=host and some volume sharing are restricted. This is a read-only example of the daemon configuration (/etc/docker/daemon.json); it needs a daemon restart and is not something to try on a shared machine:

JSON
{
  "userns-remap": "default"
}

With default, Docker creates a user called dockremap and allocates its subordinate UID range from /etc/subuid. Individual containers can opt out with docker run --userns=host.

Rootless mode goes further: the entire daemon runs as an ordinary user, with no root process at all. A container escape ends in that user's account. Installation is a script (dockerd-rootless-setuptool.sh install) on a Linux host with newuidmap available, and you then talk to a per-user socket. Limits include no privileged ports below 1024 unless configured, slower networking, and some storage drivers unavailable. The lesson Securing the Docker Daemon covers the trade-offs. Rootless is the strongest choice for developer machines and CI runners that execute untrusted code.

When to use which layer

Layer Default? Turn it up when
seccomp default profile On Never turn it off in production. Write a custom profile only for high-risk services
AppArmor / SELinux On where available Use a custom profile for services that parse untrusted input
--read-only Off Almost always, for stateless services (web, API, workers)
noexec tmpfs Off Whenever /tmp does not need to run programs
userns-remap / rootless Off Shared hosts, CI runners, anything that runs code you do not control

Avoid read-only mode for containers whose job is to write to their own filesystem, such as package managers, build containers and databases without a data volume. Put data on a volume, and keep the root read-only.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the line 'Seccomp: 2' in /proc/self/status of a container tell you?

    Mode 2 is filter mode: a seccomp filter is active. Mode 0 would mean no filter. It says nothing about how many calls are blocked.
  2. 2. A container fails to start after you add --read-only, with a 'Read-only file system' error for a cache directory. What is the best fix?

    The error names the path that must be writable. A tmpfs there keeps the rest of the filesystem read-only and the data never reaches the image layers.
  3. 3. Why is --security-opt seccomp=unconfined a poor permanent fix for an application that needs one blocked system call?

    Unconfined drops every restriction of the profile. A custom profile that allows only the extra call keeps the rest of the protection.
  4. 4. How can you prove that a running container is not writing to its own filesystem layer?

    docker diff lists every file added, changed or deleted in the container's writable layer. An empty list means nothing was written there.
  5. 5. What problem do user namespace remapping and rootless mode address?

    Both make 'root' in the container an unprivileged user on the host, so an escape does not end with real root privileges.

Summary

  • Docker applies a default seccomp profile that blocks dangerous system calls; check it with Seccomp: 2 in /proc/self/status. Never run production containers with seccomp=unconfined.
  • Custom profiles are JSON files passed with --security-opt seccomp=file.json; allow-lists are safest, but need testing.
  • AppArmor (Debian/Ubuntu) and SELinux (Fedora/RHEL) restrict files and operations per container; keep the defaults and avoid --privileged, which disables them.
  • --read-only (Compose: read_only: true) makes the root filesystem unwritable; add tmpfs or volumes only for paths that must be written, and confirm with docker diff.
  • Mount tmpfs with noexec,nosuid to stop attackers running payloads from temp directories.
  • userns-remap and rootless mode make container root an unprivileged user on the host.
  • Layers add up: capabilities, seccomp, LSM profile, read-only rootfs and no-new-privileges together make a hardened service.

Next: Securing the Docker Daemon