StackPractices
intermediate By Mathias Paulenko

Docker Image Hardening Checklist

A production-ready checklist for hardening Docker images: shrink the attack surface, enforce least privilege, and catch vulnerabilities before deployment.

Topics: devops

Overview

Most Docker images shipped to production carry more attack surface than they need: a full shell, a package manager, hundreds of packages nobody audits, and a root process waiting for one escape. When a vulnerability lands in one of those images, the blast radius includes everything the image can read, write, and call over the network.

This checklist walks through the controls that shrink that blast radius, organized the way you’d apply them to a real Dockerfile: pick a minimal base, run as non-root, lock down the filesystem and network, cap resources, keep secrets out of layers, scan and sign the result, then drop privileges at runtime. Each section pairs the checklist with working Dockerfile, Compose, or CLI examples and the commands you’d use to verify the control actually took effect.

Use it when you’re building a new production image, reviewing an existing Dockerfile before a security audit, or establishing a team-wide baseline — run it top to bottom for new work, or cherry-pick sections against an image you’re already shipping. It focuses on the image itself; for hardening the runtime, host, and orchestrator around it, pair it with a broader container security baseline template aligned with the CIS Docker Benchmark. Every file referenced on this page — the hardened Dockerfile, .dockerignore, Compose stack, seccomp profile, and CI workflow — is runnable in the companion repo.

Mermaid flowchart LR diagram

1. Base Image Selection

Why it matters

Every package in your base image is a package you’ll eventually have to patch. The default node, python, or ubuntu images ship with a shell, a package manager, and dozens of utilities that your application never runs but an attacker happily will — a shell in the image turns an RCE into an interactive session.

There are two separate pinning decisions here, and people routinely conflate them. A tag (node:20-alpine) is mutable: the registry can move it to a different image tomorrow, so your “pinned” build quietly changes underneath you. A digest (@sha256:...) is immutable: it always resolves to the exact bytes you verified. For production, pin the tag for readability and the digest for integrity.

The trade-off matrix isn’t “smaller is always better”. Alpine is tiny (7 MB) but uses musl libc instead of glibc, which occasionally breaks binaries compiled against glibc or produces subtle DNS and locale differences. Distroless removes the shell entirely — great for security, painful the first time you need to debug a running container. Keep a debug variant tagged for those moments.

1.1 Checklist

- [ ] Use official images from Docker Hub or trusted registries
- [ ] Use minimal base images (alpine, distroless, scratch)
- [ ] Pin base image version with digest (not just tag)
- [ ] Avoid :latest tag — use specific version
- [ ] Verify base image is actively maintained
- [ ] Check base image for known vulnerabilities before use
- [ ] Use multi-arch images if deploying to multiple architectures
- [ ] Document base image rationale in Dockerfile comments

1.2 Dockerfile — Pinned Base Image

# BAD: unpinned, mutable latest tag
FROM node:latest

# BETTER: version pinned — still mutable under the tag
FROM node:20.11.0-alpine

# BEST: version + immutable digest
# Get the digest with: docker buildx imagetools inspect node:20.11.0-alpine
FROM node:20.11.0-alpine@sha256:REPLACE_WITH_VERIFIED_DIGEST

# Distroless — smallest attack surface, no shell at all
FROM gcr.io/distroless/nodejs20-debian12:nonroot@sha256:REPLACE_WITH_VERIFIED_DIGEST

1.3 Base Image Comparison

Base image              | Size    | Shell | Package manager | Attack surface
────────────────────────┼─────────┼───────┼─────────────────┼──────────────────
ubuntu:22.04            | 77 MB   | Yes   | apt             | High
debian:12-slim          | 74 MB   | Yes   | apt             | Medium
alpine:3.19             | 7 MB    | Yes   | apk             | Low
distroless/nodejs20     | 125 MB  | No    | None            | Very low
scratch                 | 0 MB    | No    | None            | Minimal

1.4 How to verify

# See exactly what the digest resolves to
docker buildx imagetools inspect node:20.11.0-alpine

# Confirm the running image matches the pinned digest
docker inspect --format='{{.RepoDigests}}' myapp:latest

# Try to open a shell — should fail on distroless
docker run --rm -it gcr.io/distroless/nodejs20-debian12:nonroot sh

On registry trust: “official” images on Docker Hub (the ones with no namespace prefix, like node or alpine) are curated by Docker, and “Verified Publisher” and “Sponsored OSS” badges mark vendor-maintained images. Everything else is user-uploaded — treat random username/app images like what they are: untrusted code.

2. User Permissions

Why it matters

If your app runs as root inside the container and the process gets compromised, the attacker is root in a filesystem that’s probably mounted read-write, with whatever Linux capabilities Docker grants by default. Container escape bugs (and there have been several — CVE-2019-5736 in runc being the famous one) go from “bad” to “host compromised” much faster when the container process is UID 0.

The USER instruction in the Dockerfile is the baseline control; it should be a numeric UID, not a name. Numeric UIDs avoid surprises: Kubernetes’ runAsNonRoot checks the numeric UID, and a named user in the image’s /etc/passwd is one more file that could be modified. Running as non-root also means your app can’t accidentally write to system paths — a free integrity check.

Don’t confuse “non-root user” with “no capabilities”. Even as a non-root user, a process can still hold Linux capabilities if the container is launched with them. The user switch in the image and the capability drop at runtime (section 8) work together.

2.1 Checklist

- [ ] Container runs as non-root user
- [ ] USER directive in Dockerfile specifies non-root UID
- [ ] File ownership set to non-root user
- [ ] No sudo available in the image
- [ ] UID is numeric (not named — avoids lookup issues)
- [ ] User has minimal filesystem permissions
- [ ] Read-only access to application files
- [ ] No write access to system directories

2.2 Dockerfile — Non-Root User

# Create non-root user with specific UID
RUN groupadd -r appuser -g 1001 && \
    useradd -r -g appuser -u 1001 -m -d /home/appuser appuser

# Set ownership
COPY --chown=1001:1001 . /app
RUN chown -R 1001:1001 /app && chmod -R 550 /app

# Switch to non-root user
USER 1001:1001

# Application runs as non-root
CMD ["node", "server.js"]

2.3 Docker Compose — Runtime User

services:
  api:
    image: myapp:latest
    user: "1001:1001"
    read_only: true
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    tmpfs:
      - /tmp
      - /app/cache

2.4 How to verify

# Who is the process running as?
docker exec myapp id

# Try to write somewhere it shouldn't — should fail
docker exec myapp touch /etc/breakme

# On Kubernetes, enforce it at admission:
# securityContext.runAsNonRoot: true + runAsUser: 1001

3. Filesystem Restrictions

Why it matters

A read-only root filesystem closes a whole class of post-exploitation moves: an attacker can’t drop a webshell, replace a binary, or modify config files to persist. Anything the app legitimately needs to write — temp files, caches, upload staging — goes to a tmpfs mount, which lives in memory and dies with the container.

The .dockerignore file is your second filesystem control, and it’s the one that bites people who think they’re safe because they never COPY .env explicitly. docker build sends the entire build context to the daemon, and a careless COPY . . pulls in .git, .env, SSH keys, and test fixtures containing production credentials. Excluding them at the context level means they never even reach the daemon, let alone the image.

The third control is build hygiene: package manager caches, downloaded tarballs, and compiler artifacts left in intermediate layers still ship in the final image unless you clean them in the same RUN instruction or use a multi-stage build. A layer that installs a tool and a later layer that deletes it still contains the tool — layers are additive.

3.1 Checklist

- [ ] Read-only root filesystem enabled
- [ ] Writable paths mounted as tmpfs
- [ ] No sensitive files copied into image
- [ ] .dockerignore excludes secrets, .git, node_modules
- [ ] No build artifacts left in final image
- [ ] /tmp, /var/tmp mounted as tmpfs
- [ ] No SSH keys or credentials in image layers
- [ ] Clean package manager caches in same layer

3.2 .dockerignore

.git
.gitignore
.env
.env.*
*.pem
*.key
node_modules
npm-debug.log
Dockerfile
docker-compose.yml
coverage
test
*.md
.vscode
.idea

3.3 Dockerfile — Clean Layers

# Multi-stage build — only final artifacts in production image
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build

# Final stage — minimal image
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./

# Clean apk cache in same layer
RUN apk add --no-cache curl && rm -rf /var/cache/apk/*

USER 1001:1001
CMD ["node", "dist/server.js"]

3.4 How to verify

# Inspect what's actually in the image layers
docker history myapp:latest --no-trunc

# Or use dive for a per-layer file browser
dive myapp:latest

# Try to write to the rootfs at runtime — should fail with read_only
docker run --rm --read-only myapp:latest touch /app/breakme

4. Network and Port Restrictions

Why it matters

EXPOSE in a Dockerfile is documentation more than enforcement — the real boundary is what gets published at runtime and which Docker networks the container joins. The classic mistake is ports: - "8080:8080", which binds on 0.0.0.0 and puts your service on every interface the host has, including the public one. Binding to 127.0.0.1:8080:8080 keeps it local; putting internal services on a network marked internal: true removes external reachability entirely.

Egress is the direction people forget. An inbound-hardened container that can make arbitrary outbound connections is a great exfiltration channel — the payload phones home on port 443 and your firewall rules wave it through. Docker alone can’t do per-domain egress filtering; for that you need a network policy in Kubernetes, a proxy, or at minimum a separate egress-restricted bridge network.

Worth knowing about EXPOSE specifically: it doesn’t publish anything by itself, and skipping it doesn’t hide a port — any port the process listens on is reachable from other containers on the same network regardless. Its real value is documentation and interop: tools like Traefik, docker run -P, and compose generators read it. Declare it for every port your service actually uses, and keep the count honest — an image that exposes 3000-9000 tells the reader nothing.

4.1 Checklist

- [ ] Only necessary ports exposed (EXPOSE directive)
- [ ] No host network mode (--network=host)
- [ ] Container connected to specific Docker network
- [ ] No ports bound to 0.0.0.0 unless public-facing
- [ ] Internal services bound to Docker network only
- [ ] Docker network has IP range restriction
- [ ] No privileged port mapping (< 1024) without justification
- [ ] Egress traffic filtered if possible

4.2 Docker Compose — Network Isolation

networks:
  frontend:
    driver: bridge
    ipam:
      config:
        - subnet: 172.20.0.0/16
  backend:
    driver: bridge
    internal: true  # No external access at all
    ipam:
      config:
        - subnet: 172.21.0.0/16

services:
  api:
    networks:
      - frontend
      - backend
    ports:
      - "127.0.0.1:8080:8080"  # Bind to localhost only

  database:
    networks:
      - backend  # Internal only — no port exposure
    ports: []  # No ports published

4.3 How to verify

# What ports are actually published and where do they bind?
docker port myapp
docker inspect --format='{{json .NetworkSettings.Ports}}' myapp | jq

# Which networks is the container on?
docker inspect --format='{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' myapp

# From the container, can it reach the internet on a backend-only network?
docker exec myapp sh -c "wget -q -T 3 -O- https://google.com && echo EGRESS_OPEN || echo EGRESS_BLOCKED"

5. Resource Limits

Why it matters

Unbounded containers are a self-inflicted DoS: a memory leak, a fork bomb, or a traffic spike on one service starves everything else on the host. Memory and CPU limits turn that catastrophic scenario into a bounded one — the offending container gets OOM-killed or throttled while its neighbors keep serving.

--pids-limit deserves a special mention because it’s rarely set and it’s the direct counter to fork bombs: a process can’t spawn unbounded children once the PID cgroup is capped. The restart policy and health check complement the limits — a service that hits its memory limit repeatedly is signaling a bug you want surfaced, not silently restarted in a loop. A properly configured Docker health check gives you that visibility through docker inspect and orchestrator events.

One caveat on --oom-kill-disable: it exists, it’s tempting, and you should almost never use it. A container that can’t be OOM-killed pushes the host kernel to kill whatever it can, which is often a different container. Set real limits and fix the leak instead.

5.1 Checklist

- [ ] Memory limit set (--memory)
- [ ] CPU limit set (--cpus)
- [ ] Memory reservation set (--memory-reservation)
- [ ] PIDs limit set (--pids-limit)
- [ ] OOM killer preference reviewed (--oom-kill-disable almost never)
- [ ] Restart policy configured
- [ ] Health check configured
- [ ] Logging driver configured with size limits

5.2 Docker Compose — Resource Limits

services:
  api:
    image: myapp:latest
    deploy:
      resources:
        limits:
          cpus: "2.0"
          memory: 512M
          pids: 100
        reservations:
          cpus: "0.5"
          memory: 256M
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

Note: the deploy.resources block only takes effect under docker compose v2+ orchestration semantics and Docker Swarm; for plain docker run use the equivalent flags (--memory, --cpus, --pids-limit). If your Compose file ignores limits silently, that’s why — verify with docker inspect.

5.3 How to verify

# Confirm limits actually applied
docker inspect --format='{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}} {{.HostConfig.PidsLimit}}' myapp

# Watch live usage
docker stats myapp

# Confirm the log rotation took effect
docker inspect --format='{{json .HostConfig.LogConfig}}' myapp | jq

6. Secret Management

Why it matters

Secrets end up in images through three well-worn paths: ENV/ARG values baked into layers, files copied in by an overly broad COPY, and build args passed on the command line. All three are recoverable by anyone who can pull the image — docker history and docker inspect expose build args and env vars in plain sight, and deleted files live on in earlier layers.

The two correct patterns separate build-time from runtime. BuildKit secret mounts (--mount=type=secret) give a build step temporary access to a secret file without writing it into any layer — the mount vanishes when the instruction completes. Runtime secrets come from outside the image entirely: Docker secrets, a mounted file, an external vault, or orchestrator-managed secret stores. The rule of thumb: an image should be safe to publish to a public registry without leaking anything.

If you already shipped an image with a secret inside, rotating the secret is mandatory — rebuilding without it doesn’t help anyone who pulled the compromised layer. For the full pattern including rotation and vault backends, see the Docker secrets management recipe.

6.1 Checklist

- [ ] No secrets in environment variables in Dockerfile
- [ ] No secrets in ARG or ENV directives
- [ ] Secrets loaded from Docker secrets or external vault
- [ ] No secrets in image labels
- [ ] No secrets in build args (visible in image history)
- [ ] Use BuildKit secret mounting for build-time secrets
- [ ] Runtime secrets via Docker secrets or mounted volumes
- [ ] Secret rotation does not require image rebuild

6.2 BuildKit Secret Mounting

# syntax=docker/dockerfile:1.6

# Build-time secret — never stored in image layers
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    npm ci --production

# Runtime — use Docker secrets
# docker secret create npmrc /path/to/.npmrc
# Build with a secret mounted, without baking it in
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:latest .

6.3 Docker Compose — Secrets

services:
  api:
    image: myapp:latest
    secrets:
      - db-password
      - api-key
    environment:
      DB_PASSWORD_FILE: /run/secrets/db-password
      API_KEY_FILE: /run/secrets/api-key

secrets:
  db-password:
    file: ./secrets/db-password.txt
  api-key:
    external: true
    name: production-api-key

6.4 How to verify

# Scrub history for secrets before shipping
docker history myapp:latest --no-trunc | grep -iE "password|secret|key|token"

# Check env vars in the image config
docker inspect --format='{{json .Config.Env}}' myapp | jq

# Scan the image filesystem for common secret patterns
trivy image --scanners secret myapp:latest

7. Vulnerability Scanning

Why it matters

Hardening shrinks the attack surface; scanning tells you what’s still exposed inside it. The two belong together in CI: scan every image on every build, fail the pipeline on HIGH and CRITICAL findings that have a fix (--ignore-unfixed keeps the gate from firing on CVEs you can’t do anything about), and run a scheduled scan on images already in production — new CVEs appear daily against dependencies that were clean when you shipped.

Running two scanners sounds redundant but genuinely isn’t: Trivy, Grype, and Docker Scout pull from different vulnerability databases and differ on OS package detection. A finding caught by one and missed by the other is a routine occurrence. Pick one as the CI gate and a second as a nightly check.

SBOM generation is the quiet win here. A CycloneDX or SPDX manifest attached to each image means the next time a “log4shell-class” CVE drops, you answer “are we affected?” with a grep instead of a guessing game. Pair it with image signing so downstream consumers can verify the SBOM actually describes the artifact they’re running.

The nightly re-scan is the piece most teams skip because the image in the registry “hasn’t changed” — but the vulnerability database has. An image that passed the gate on Monday picks up a new CRITICAL on Friday without anyone touching it. Scan the deployed digest directly (trivy image registry.example.com/myapp@sha256:...) on a schedule and alert on new findings; that’s what turns scanning from a one-time checkbox into monitoring.

7.1 Checklist

- [ ] Trivy scan in CI pipeline (blocks on HIGH/CRITICAL)
- [ ] Grype or Snyk Container scan as secondary check
- [ ] Base image scanned before use
- [ ] Scan runs on every image build in CI
- [ ] Scan runs nightly on production images
- [ ] CVE findings tracked and remediated
- [ ] SBOM (Software Bill of Materials) generated
- [ ] Image signed with Cosign or Notation

7.2 CI Pipeline — Trivy Scan

# GitHub Actions
name: Container Security
on:
  push:
    branches: [main]
  pull_request:

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build image
        run: docker build -t myapp:${{ github.sha }} .

      - name: Trivy scan
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: myapp:${{ github.sha }}
          format: json
          output: trivy-report.json
          exit-code: 1
          severity: HIGH,CRITICAL
          ignore-unfixed: true

      - name: Generate SBOM
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: myapp:${{ github.sha }}
          format: cyclonedx
          output: sbom.json

      - name: Sign image with Cosign
        run: |
          cosign sign --key ${{ secrets.COSIGN_KEY }} myapp:${{ github.sha }}

7.3 Trivy Scan Commands

# Scan image for vulnerabilities
trivy image myapp:latest --severity HIGH,CRITICAL --exit-code 1

# Scan and ignore unfixed vulnerabilities
trivy image myapp:latest --ignore-unfixed --severity HIGH,CRITICAL

# Generate SBOM
trivy image --format cyclonedx --output sbom.json myapp:latest

# Scan Dockerfile for misconfigurations
trivy config Dockerfile --severity HIGH,CRITICAL

The container security scanning recipe covers a fuller scanning setup with report publishing and baseline files. Official docs: Trivy, Cosign/Sigstore.

8. Capability and Privilege Restrictions

Why it matters

Docker’s default capability set is a compromise — the clearly dangerous ones are gone, but two dozen capabilities a typical web app never needs remain — CHOWN, SETUID, MKNOD, NET_RAW (which enables packet crafting and is a known amplifier for attacks). --cap-drop=ALL starts from zero; you add back only what the application provably uses. NET_BIND_SERVICE is the common add-back for binding ports below 1024, though with a non-root user the usual fix is to just listen on 8080 instead.

no-new-privileges is the underrated control: it prevents any process in the container from gaining privileges through setuid binaries or file capabilities — even if a setuid executable somehow lands in the image, it stays inert. Seccomp filters the syscall surface itself; Docker’s default profile blocks roughly 60 syscalls, and it’s already on unless you explicitly disable it. AppArmor and SELinux are host-level complements — they’re worth enabling where the distro supports them, but they’re outside the image’s control.

8.1 Checklist

- [ ] All Linux capabilities dropped (--cap-drop=ALL)
- [ ] Only required capabilities added back (--cap-add)
- [ ] No privileged mode (--privileged)
- [ ] no-new-privileges flag set
- [ ] No host PID namespace (--pid=host)
- [ ] No host IPC namespace (--ipc=host)
- [ ] No host UTS namespace (--uts=host)
- [ ] Seccomp profile applied (default or custom)
- [ ] AppArmor profile applied
- [ ] SELinux labels applied if available

8.2 Docker Run — Hardened

docker run \
  --user 1001:1001 \
  --read-only \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  --security-opt=no-new-privileges:true \
  --security-opt=seccomp=seccomp-profile.json \
  --memory=512m \
  --cpus=2.0 \
  --pids-limit=100 \
  --tmpfs /tmp:rw,size=10m \
  --tmpfs /app/cache:rw,size=50m \
  --network=backend \
  --restart=unless-stopped \
  myapp:latest

8.3 How to verify

# Which capabilities does the process actually hold?
docker exec myapp grep CapEff /proc/1/status
# Decode the hex mask: capsh --decode=<value>

# Is the default seccomp profile active?
docker inspect --format='{{.HostConfig.SecurityOpt}}' myapp

# The nuclear self-test — this should all fail:
docker exec myapp sh -c "ping -c1 8.8.8.8; mount -t tmpfs none /mnt; kill -9 1"

Common Mistakes

These are the failures that show up most often in real Dockerfiles, ordered roughly by how much damage they cause:

  • COPY . . without a .dockerignore: the single most common way secrets end up in images. The build context ships everything — .git, .env, local .npmrc — and one broad COPY pulls it into a layer. Even if a later instruction deletes it, the file stays recoverable in history. Exclude at the context level first.
  • Pinning the tag but not the digest: FROM node:20-alpine feels pinned but isn’t. Tags move; a security patch to the upstream image silently changes your build. For reproducible, auditable builds you need @sha256:.
  • Running apt-get update in one layer and apt-get install in another: between the two, the package index goes stale and you install old versions — or the build fails weeks later when the index rots. Always chain them: apt-get update && apt-get install -y ... in one RUN, then clean /var/lib/apt/lists in the same layer.
  • Adding --privileged “just to make it work”: usually what’s actually needed is a single capability (SYS_ADMIN, NET_ADMIN) or a device mount. Privileged mode disables almost every isolation mechanism — it’s the hardening equivalent of turning off the firewall because a rule was wrong.
  • Setting resource limits only in deploy.resources on non-Swarm Compose: the block is silently ignored by docker compose up in some configurations, leaving you with no limits and a false sense of safety. Verify with docker inspect, don’t assume the YAML did what it says.
  • Removing a secret by deleting the ENV line: the value already lives in a previous layer. Rebuilding doesn’t purge history — rotate the credential, then remove the line.
  • Installing a shell or debugging tools in production “just in case”: every convenience binary is a gift to an attacker. Use a :debug variant of your distroless base for emergencies instead of shipping tools permanently.

When Not to Use This Checklist

A few cases where parts of this list don’t apply:

  • Local development images: read-only filesystems and capability drops fight hot-reload tooling, debuggers, and dev servers. Keep a separate dev image; don’t weaken prod to match dev.
  • One-shot CI/build containers: ephemeral containers that never face production traffic mainly need the secrets and base-image sections; the runtime controls are mostly noise there.
  • Distroless for interactive debugging: if the team’s workflow depends on docker exec into a shell, adopt distroless gradually — keep a :debug variant available or you’ll train people to bypass the hardening.
  • Kubernetes-managed workloads: K8s’ securityContext, NetworkPolicy, and Pod Security Standards duplicate much of sections 2, 4, 5, and 8 — set them at the pod spec level there, and treat the image-level controls as defense in depth, not the primary enforcement.

Further Reading

See Also

Frequently Asked Questions

What's the difference between Alpine and Distroless base images?

Alpine is a minimal Linux distribution (7 MB) with a shell, package manager (apk), and busybox utilities. It's easy to debug but has a larger attack surface than distroless — and its musl libc can behave differently than glibc for some binaries. Distroless images contain only your application runtime and its dependencies: no shell, no package manager, no utilities. They're harder to debug but leave an attacker with almost nothing to work with. Use Alpine where debuggability matters, distroless for production, and keep a :debug distroless variant around for emergencies.

How do I debug a container with a read-only filesystem?

Mount tmpfs for the writable paths your app needs: --tmpfs /tmp --tmpfs /app/cache. For interactive debugging, temporarily drop read-only with docker run --rm -it myapp:latest sh (if the image has a shell). Distroless images have a :debug variant that bundles busybox. For running containers, docker exec works when a shell exists; otherwise docker cp tools in or use kubectl debug on Kubernetes, which attaches an ephemeral debug container without touching the image.

Should I use Docker Scout, Trivy, or Grype for vulnerability scanning?

All three are effective. Trivy is the most widely adopted open-source scanner, with broad CVE coverage and strong CI integration. Grype (from Anchore) is also open-source and pairs naturally with Syft for SBOM work. Docker Scout is built into Docker Desktop and Hub, so it's the lowest-friction option in a Docker-centric setup. Whichever you pick as the CI gate, run a second scanner nightly — their vulnerability databases differ enough that findings regularly appear in one but not the other.

How do I reduce Docker image size?

Multi-stage builds do the heavy lifting: compile in a builder stage, copy only the artifacts into a minimal final stage. Clean package caches inside the same RUN layer (apk add --no-cache, or apt-get ... && rm -rf /var/lib/apt/lists/*), exclude tests and docs via .dockerignore, and use npm ci --production or equivalent to skip dev dependencies. Then inspect the result with dive — it shows per-layer sizes and flags wasted bytes you didn't know were there.

What's image signing and why do I need it?

Image signing cryptographically proves an image came from your pipeline and wasn't modified in the registry. Tools like Cosign (Sigstore) sign images with keys or keylessly via OIDC in CI; consumers verify the signature before pulling. It matters because registries get compromised and tags get moved — without signature verification, myapp:v1.2.3 could point to something an attacker pushed. Enforce verification in your deploy platform: Sigstore's policy controller on Kubernetes, or Docker Content Trust (DOCKER_CONTENT_TRUST=1) for simpler setups.