# Container security: scanning, non-root, runtime limits and secrets

Harden containers in four layers: scan images for vulnerabilities, run as non-root, drop capabilities, and keep secrets out of images, history and environment variables.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 11. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/11-security

## What you will learn

- Scan an image for known vulnerabilities and decide what to fix first
- Run containers as a non-root user, in the Dockerfile and at run time
- Drop Linux capabilities and block privilege escalation with no-new-privileges
- Know which flags break isolation, such as --privileged and mounting the Docker socket
- Pass secrets at build time with BuildKit secret mounts and at run time as files, never through ARG or ENV

## Four layers

Before containers, teams secured the host and assumed the application inherited that protection. Containers add
isolation, but they still share the host kernel and can contain vulnerable packages, root processes or exposed
credentials. Docker security works in layers: reduce what is in the image, limit who the process runs as, restrict
what it can do, and keep secrets outside the image. In this lesson, you'll apply those checks to the price API and
verify the runtime settings rather than assuming the defaults are safe.

| Layer           | Question                                        | Tool                                               |
| --------------- | ----------------------------------------------- | -------------------------------------------------- |
| the **image**   | does it contain known-vulnerable software?      | a scanner: Grype, Trivy, Docker Scout              |
| the **user**    | if the app is taken over, is the attacker root? | `USER`, `--user`                                   |
| the **runtime** | what can the process do to the kernel?          | capabilities, no-new-privileges, read-only, limits |
| the **secrets** | can anyone read passwords from the image?       | secret mounts and files, never `ARG` or `ENV`      |

The image layer is checked before a container starts. User and runtime controls limit the damage if the app is
compromised. Secret handling prevents credentials from being copied into the image in the first place. No single
control covers every failure, so apply the layers together and verify them on the running container. Start with
the smallest image and least privilege that still lets the application do its job.

> **Figure.** Four layers around the price-api container. The image: a small base, scanned for known vulnerabilities with Trivy, Grype or Docker Scout. The user: the process runs as a non-root user, so a takeover is not root. The runtime: capabilities dropped, no-new-privileges, a read-only file system and memory and CPU limits restrict what the process can do to the kernel. The secrets: mounted as files at run time, never baked into the image with ARG or ENV.
>
> Image, user, runtime and secrets: each layer limits the damage if the one before fails.

## Image scanning

A scanner lists the packages in an image and matches them against vulnerability databases. Here is Grype on
the single-stage image from lesson 7, scanning a saved copy so the scanner never touches the Docker socket:

```sh
$ docker save price-api:single -o single.tar
$ docker run --rm -v "$PWD":/scan:ro anchore/grype:v0.119.0 docker-archive:/scan/single.tar
NAME        INSTALLED  FIXED IN  TYPE  VULNERABILITY   SEVERITY  EPSS          RISK
libssl3     3.5.8-r0             apk   CVE-2026-84784  High      0.4% (32nd)   0.3
zlib        1.3.2-r0   1.3.2-r1  apk   CVE-2026-85091  High      0.4% (27th)   0.3
libcrypto3  3.5.8-r0             apk   CVE-2026-72897  High      0.3% (17th)   0.2
busybox     1.37.0-r31           apk   CVE-2025-60876  Medium    0.3% (22nd)   0.2
…
```

How to read it:

- **Every finding here is in the base image** (Alpine's OpenSSL, zlib, BusyBox), none in your code. A smaller
  base has fewer packages and fewer findings: run the same scan on the distroless image and compare.
- **FIXED IN** says a patched version exists: rebuild on an updated base (`docker build --pull`) and rescan.
  Empty means no fix yet; decide whether the vulnerable code is reachable.
- **EPSS** estimates how likely the CVE is to be exploited soon. Fix High and Critical with a fix first.

Scan in CI and fail the build on Critical findings that have a fix (`grype --fail-on critical --only-fixed`),
and rescan old images: new CVEs are published for software that hasn't changed.

> **Video.** [Docker vulnerability scanning tool | Trivy](https://www.youtube.com/watch?v=pZumqxTwLNw) (kubernetesWay)

## Non-root users

By default the process in a container runs as **root**, the same user ID 0 as root on the host, held back only
by namespaces and capabilities. Run as an ordinary user:

```sh
$ docker run --rm alpine:3.22 id
uid=0(root) gid=0(root) groups=0(root),…
$ docker run --rm --user 1000:1000 alpine:3.22 sh -c 'id; touch /etc/x'
uid=1000 gid=1000 groups=1000
touch: /etc/x: Permission denied
```

Better, set it in the image so nobody forgets: `USER nonroot` in distroless, or in your own image:

```dockerfile
RUN addgroup -S app && adduser -S -G app app
USER app
```

A non-root process can't bind ports below 1024, so listen on 8080 and publish `-p 80:8080`.

The important boundary is the process user inside the container. Root there is still restricted by namespaces
and capabilities, but it has more authority than the application needs in most cases. `USER` in the image makes
the safe choice the default for every run; `--user` can override it at runtime. Check the effective UID rather
than relying only on the Dockerfile text. If the app needs to write files, give it a specific writable directory
and ownership instead of making the whole filesystem writable or switching back to root.

> **Video.** [Docker Security Best Practices | Run Containers as Non-Root User [Docker HomeLab EP8 | 2025]](https://www.youtube.com/watch?v=klbgi1d1UpY) (LearnwithDevOpsEngineer)

## Runtime security

Root inside a container gets a reduced set of Linux **capabilities**. Drop them all, and root can't even change a
file's owner:

```sh
$ docker run --rm alpine:3.22 chown nobody /etc/hostname && echo chown-ok
chown-ok
$ docker run --rm --cap-drop ALL alpine:3.22 chown nobody /etc/hostname
chown: /etc/hostname: Operation not permitted
$ docker run --rm --cap-drop ALL --security-opt no-new-privileges alpine:3.22 grep -E 'NoNewPrivs|CapEff' /proc/self/status
CapEff:	0000000000000000
NoNewPrivs:	1
```

`CapEff` 0 means no capabilities; `NoNewPrivs` 1 means a setuid binary can't raise privileges. A hardened
service combines them:

Capabilities split root's broad Linux authority into smaller permissions. Dropping them reduces the actions a
compromised process can ask the kernel to perform. `no-new-privileges` prevents a process from gaining extra
privileges through setuid programs. A read-only root filesystem blocks accidental writes to application files,
while explicit limits keep one container from consuming all host memory or CPU. Start with these restrictions,
then add one capability only when a documented requirement and a test prove it is needed. Do not remove the
boundary just because a permission error appeared; first identify the exact operation that failed.

```sh
$ docker run -d --name api --user 65532:65532 --cap-drop ALL --security-opt no-new-privileges \
    --read-only --tmpfs /tmp --memory 256m --pids-limit 100 -p 127.0.0.1:8080:8080 price-api:multi
```

> **Flags that switch isolation off.** `--privileged` gives the container every capability and access to host devices. `-v /var/run/docker.sock:/var/run/docker.sock` lets it control Docker, which is control of the host. `--pid host`, `--network host` and mounting `/` remove whole namespaces. Each one needs a written reason, never "it made the error go away".

## Secrets

Anything in a layer, an `ARG` or an `ENV` can be read by anyone who has the image:

```sh
$ docker build --build-arg API_TOKEN=s3cr3t-token-123 -t leak:bad -f Dockerfile.bad .
$ docker history leak:bad --no-trunc --format '{{.CreatedBy}}' | grep -o 'API_TOKEN=[^ ]*' | head -1
API_TOKEN=s3cr3t-token-123
```

For build time, use a BuildKit **secret mount**. The secret is a file only while that one `RUN` runs:

```dockerfile
# syntax=docker/dockerfile:1
FROM alpine:3.22
RUN --mount=type=secret,id=api_token test -s /run/secrets/api_token && echo "token present at build time"
```

```sh
$ docker build --secret id=api_token,src=token.txt -t leak:good -f Dockerfile.good .
#9 1.536 token present at build time
$ docker history leak:good --no-trunc | grep -c s3cr3t
0
$ docker run --rm leak:good ls /run/secrets
ls: /run/secrets: No such file or directory
```

At run time, mount secrets as files: Compose `secrets:` (lesson 9), Docker Swarm secrets or Kubernetes
secrets, read by the app from `/run/secrets/…`. Many official images accept `_FILE` variables for this, like
`POSTGRES_PASSWORD_FILE`. And a `.dockerignore` keeps `.env` files out of `COPY . .` in the first place.

Build-time and runtime secrets solve different stages. A build secret is available to one BuildKit step, such as
downloading a private dependency, but is not committed to an image layer. A runtime secret is mounted only for
the service that needs it. `ARG` can appear in build history, and `ENV` becomes image configuration; deleting a
secret in a later layer does not erase it from an earlier layer. If a credential was ever included in an image,
rotate it first. Then rebuild and remove exposed tags, while assuming someone may already have pulled a copy.

> **In production.** Scan every image in CI and on a schedule, rebuild on patched bases, run as non-root with all capabilities dropped, a read-only filesystem and limits, and keep secrets in a secret manager. If a secret ever reached an image or a registry, rotate it: deleting the tag doesn't delete copies already pulled.

## Reduce the container's attack surface

An SBOM lists installed components; a vulnerability scan prioritises fixes. Docker Scout can provide both, while
Trivy or Grype are local alternatives. Signing with cosign only helps when verification is enforced at deployment.

```sh
$ docker scout sbom price-api:multi
$ docker scout cves price-api:multi
$ docker run --rm --user 65532:65532 --cap-drop ALL --security-opt no-new-privileges \
    --read-only --tmpfs /tmp:rw,noexec,nosuid alpine:3.22 id
```

Start with a non-root UID, all capabilities dropped, no-new-privileges and a read-only root. Seccomp and AppArmor
add syscall/profile boundaries; do not use `--privileged` to hide an unexplained failure.

An SBOM is an inventory of components in the image. A scanner compares that inventory with known vulnerability
data and helps prioritize updates; it cannot prove the app has no flaws. Signing records who built an image, but
the deployment system must verify the signature for that check to affect what runs. Combine these controls with
small base images, pinned inputs and routine rebuilds. Start with the least privilege the service needs, then
verify the live container's user, capabilities, filesystem mode and resource limits. A hardened image is only
useful if the deployment keeps those settings in force.

## Mission: Harden the price API

Run the price API with no capabilities, no privilege escalation, a read-only filesystem, a non-root user and limits; prove it still answers. Then prove a build argument leaks into history while a secret mount does not.

- You need: Docker and the price-api:multi image from lesson 7
- You'll have: A healthy hardened container with CapEff 0, and docker history showing the leaked ARG but not the secret

```sh
$ docker run -d --name api --user 65532:65532 --cap-drop ALL --security-opt no-new-privileges \
    --read-only --memory 256m --pids-limit 100 -p 127.0.0.1:8090:8080 -e APP_VERSION=hardened price-api:multi
$ curl -s localhost:8090/health
{"status":"ok","version":"hardened"}
$ docker inspect api --format '{{.HostConfig.CapDrop}} {{.HostConfig.ReadonlyRootfs}} {{.Config.User}}'
[ALL] true 65532:65532
$ printf 'FROM alpine:3.22\nARG API_TOKEN\nRUN test -n "$API_TOKEN"\n' > Dockerfile.bad
$ docker build -q --build-arg API_TOKEN=s3cr3t -t leak:bad -f Dockerfile.bad . && docker history leak:bad --no-trunc | grep -c s3cr3t
$ docker rm -f api
```

The API needs none of the root powers it would get by default, and nothing breaks without them. That's the
habit: start from nothing and add back only what fails for a reason you understand.

## Try it

- Scan an image you use with Grype or Trivy and find its High and Critical findings.
- Compare the scan of a full base image with a distroless or alpine one.
- Run `grep CapEff /proc/self/status` in a container with and without `--cap-drop ALL`.
- Build an image with `--build-arg API_TOKEN=…` and find the token in docker history.
- Rebuild it with a secret mount and check the token is gone from history.
- Run a container with `--user 1000:1000` and try to write to /etc.

## Quiz

1. A scan reports a High CVE in libssl3 with a fixed version available. What is the usual fix?
   - Ignore it
   - **Rebuild on an updated base image (or upgrade the package), then rescan** (answer)
   - Delete the scanner
   - Run the container as root
   Why: Most findings come from the base image. Rebuilding regularly on a patched base fixes them; fewer packages means fewer findings.

2. Why is --build-arg API_TOKEN=… a bad way to pass a secret?
   - It is slow
   - **Build arguments are recorded in the image history, so anyone with the image can read the token** (answer)
   - It only works with Compose
   - It needs root
   Why: docker history --no-trunc showed API_TOKEN=s3cr3t-token-123. Use RUN --mount=type=secret instead: the secret is never written to a layer.

3. What does --cap-drop ALL do?
   - Removes the root user
   - **Removes every Linux capability, so even root inside can't do things like chown files or bind low ports** (answer)
   - Limits CPU
   - Drops all network traffic
   Why: Docker already gives a reduced set; dropping all and adding back only what's needed (--cap-add NET_BIND_SERVICE) is least privilege.

4. Why is mounting /var/run/docker.sock into a container dangerous?
   - It is slow
   - **The container can then control Docker, start a privileged container and take over the host** (answer)
   - It breaks DNS
   - It is not dangerous
   Why: Socket access equals root on the host (lesson 3). Same for --privileged, which turns off most isolation.

5. Where should a container read a database password at run time?
   - From an ENV line in the Dockerfile
   - **From a file mounted from a secret store, such as /run/secrets/db_password** (answer)
   - From the image tag
   - From a public repository
   Why: Environment variables show up in docker inspect and in crash dumps. Files from Compose secrets, Swarm or Kubernetes secrets are safer.

## Resources

- [Docker Docs: Docker Engine security](https://docs.docker.com/engine/security/) (Docker Docs)
- [Docker Docs: build secrets](https://docs.docker.com/build/building/secrets/) (Docker Docs)
- [OWASP Docker Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html) (OWASP)
- [Grype vulnerability scanner](https://github.com/anchore/grype) (Anchore)
- [Trivy vulnerability scanner](https://trivy.dev/) (Aqua Security)
