Docker Labs · Lab 6 of 6

Production-Grade Images: Hardened, Scanned and Built in CI

Build an image the way security reviews expect: pinned base digests, non-root distroless runtime, a health check without a shell, read-only filesystem, dropped capabilities, version and git-SHA tags, a Trivy scan that gates CI, an SBOM, and a GitHub Actions pipeline that builds, scans and pushes.

Environment
Production
Level
Advanced
Time
About 60 min
Cost
Free for public repositories

You will build

A 16 MB image that runs as an unprivileged user with nothing writable but /tmp, passes a vulnerability scan, ships with an SBOM, and is built and pushed by CI only after the scan passes.

Members can save this page, take notes and track progress. See membership · Sign in

Trivy runs from its official image, so there is nothing to install. The first scan downloads its vulnerability database (about 80 MB) into a cache volume.

Base-image digests change whenever the publisher rebuilds the image; use the digests your own command prints. Container IDs, image IDs, timestamps and sizes will differ on your machine; everything else should match.

Cost: the builds and scans run on your computer; GitHub Actions and GitHub Container Registry are free for public repositories.

Project structure

secure-api/
├── main.go                    # API with a built-in -healthcheck mode
├── go.mod
├── Dockerfile                 # pinned digests, non-root, HEALTHCHECK
├── .dockerignore
├── compose.yaml               # the same hardening, declared
└── .github/
    └── workflows/
        └── image.yml          # build → scan → push

Download starter filesDownload finished project

Steps

  1. 1Look up the base-image digests

    A tag like 1.26-alpine moves whenever the image is rebuilt. A digest never changes. Pinning the digest makes builds reproducible; a bot (Renovate, Dependabot) then proposes updates you review.

    Run
    docker buildx imagetools inspect golang:1.26-alpine --format '{{.Manifest.Digest}}'
    docker buildx imagetools inspect gcr.io/distroless/static-debian13:nonroot --format '{{.Manifest.Digest}}'
    

    Expected output

    sha256:ecb67f987aa1a57794c91d19ade7ae0209f2f0f5496aaef9e6ae85ddf92d02ab
    sha256:8ce6dd87e9823c5b48dcfb2c8604714ccb351ce59607327bcc4957448da279b5
  2. 2Write the API with a self health check

    Distroless images have no shell, curl or wget, so HEALTHCHECK can't call them. The binary checks itself instead: server -healthcheck requests /health and exits 0 or 1.

    main.go
    package main
    
    import (
    	"encoding/json"
    	"flag"
    	"log"
    	"net/http"
    	"os"
    	"time"
    )
    
    var version = "dev" // set at build time with -ldflags "-X main.version=..."
    
    func main() {
    	healthcheck := flag.Bool("healthcheck", false, "check the running server and exit")
    	flag.Parse()
    
    	port := os.Getenv("PORT")
    	if port == "" {
    		port = "8080"
    	}
    
    	// The runtime image has no shell or curl, so the binary checks itself for HEALTHCHECK.
    	if *healthcheck {
    		client := http.Client{Timeout: 2 * time.Second}
    		resp, err := client.Get("http://127.0.0.1:" + port + "/health")
    		if err != nil || resp.StatusCode != http.StatusOK {
    			os.Exit(1)
    		}
    		os.Exit(0)
    	}
    
    	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    		w.Header().Set("Content-Type", "application/json")
    		json.NewEncoder(w).Encode(map[string]string{"message": "hello from a hardened container", "version": version})
    	})
    	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
    		w.Write([]byte("ok"))
    	})
    	log.Printf("version %s listening on :%s as uid %d", version, port, os.Getuid())
    	log.Fatal(http.ListenAndServe(":"+port, nil))
    }
    
  3. 3Declare the module

    go.mod
    module example.com/secure-api
    
    go 1.26
    
  4. 4Write the hardened Dockerfile

    Digests pinned, version injected at build time, OCI labels for traceability, nonroot base with an explicit numeric USER, and a health check that needs no shell.

    Dockerfile
    # syntax=docker/dockerfile:1
    
    # Base images pinned by digest: a rebuild next month uses exactly the same bases.
    FROM golang:1.26-alpine@sha256:ecb67f987aa1a57794c91d19ade7ae0209f2f0f5496aaef9e6ae85ddf92d02ab AS build
    WORKDIR /src
    COPY go.mod ./
    RUN go mod download
    COPY . .
    ARG VERSION=dev
    RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /server .
    
    FROM gcr.io/distroless/static-debian13:nonroot@sha256:8ce6dd87e9823c5b48dcfb2c8604714ccb351ce59607327bcc4957448da279b5
    ARG VERSION=dev
    LABEL org.opencontainers.image.title="secure-api" \
          org.opencontainers.image.version="${VERSION}" \
          org.opencontainers.image.source="https://github.com/your-org/secure-api"
    COPY --from=build /server /app/server
    USER 65532:65532
    EXPOSE 8080
    HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD ["/app/server", "-healthcheck"]
    ENTRYPOINT ["/app/server"]
    
  5. 5Ignore what the build doesn't need

    .dockerignore
    .git
    .github
    *.md
    Dockerfile
    .dockerignore
    sbom.cdx.json
    
  6. 6Build with a version tag and a git-SHA tag

    The semantic version says what it is; the commit SHA says exactly which code. Both point at the same image ID.

    Run
    git init -q && git add -A && git commit -qm "secure-api 1.0.0"
    GIT_SHA=$(git rev-parse --short HEAD)
    docker build --build-arg VERSION=1.0.0 -t lab-secure:1.0.0 -t lab-secure:sha-$GIT_SHA .
    docker images lab-secure
    

    Expected output

    ...
    IMAGE                    ID             DISK USAGE   CONTENT SIZE   EXTRA
    lab-secure:1.0.0         fb76eb5bc072       15.9MB         3.64MB
    lab-secure:sha-b290db1   fb76eb5bc072       15.9MB         3.64MB
  7. 7Check what's baked into the image

    Run
    docker image inspect lab-secure:1.0.0 --format 'User={{.Config.User}} Healthcheck={{json .Config.Healthcheck.Test}} Version={{index .Config.Labels "org.opencontainers.image.version"}}'
    

    Expected output

    User=65532:65532 Healthcheck=["CMD","/app/server","-healthcheck"] Version=1.0.0
  8. 8Run it locked down

    --read-only makes the root filesystem unwritable (a tmpfs gives a small writable /tmp), --cap-drop ALL removes every Linux capability, no-new-privileges blocks privilege escalation, and memory and process limits contain a runaway.

    Run
    docker run -d --name lab-secure --read-only --tmpfs /tmp:rw,size=16m --cap-drop ALL --security-opt no-new-privileges:true --memory 64m --pids-limit 100 -p 8080:8080 lab-secure:1.0.0
    sleep 12
    docker ps --filter name=lab-secure --format 'table {{.Names}}\t{{.Status}}'
    curl -s localhost:8080/
    docker logs lab-secure
    

    Expected output

    ...
    NAMES        STATUS
    lab-secure   Up 13 seconds (healthy)
    {"message":"hello from a hardened container","version":"1.0.0"}
    2026/11/26 01:50:05 version 1.0.0 listening on :8080 as uid 65532
    Check:

    Status (healthy) and the log says uid 65532, not 0 (root).

  9. 9Confirm the hardening

    There is no shell to break into, and the process runs as UID 65532 on the host too.

    Run
    docker inspect lab-secure --format 'Health={{.State.Health.Status}} ReadOnly={{.HostConfig.ReadonlyRootfs}} CapDrop={{.HostConfig.CapDrop}} SecurityOpt={{.HostConfig.SecurityOpt}}'
    docker exec lab-secure sh
    docker top lab-secure -o pid,uid,args
    

    Expected output

    Health=healthy ReadOnly=true CapDrop=[ALL] SecurityOpt=[no-new-privileges:true]
    OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH
    PID                 UID                 COMMAND
    1853117             65532               /app/server
  10. 10Scan the image with Trivy

    Run
    docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v lab-trivy-cache:/root/.cache/ aquasec/trivy:0.76.2 image --severity HIGH,CRITICAL --no-progress lab-secure:1.0.0
    

    Expected output

    ...
    2026-11-26T01:50:30Z	INFO	Detected OS	family="debian" version="13.8"
    2026-11-26T01:50:30Z	INFO	[debian] Detecting vulnerabilities...	os_version="13" pkg_num=6
    2026-11-26T01:50:30Z	INFO	Number of language-specific files	num=1
    2026-11-26T01:50:30Z	INFO	[gobinary] Detecting vulnerabilities...
    
    Report Summary
    
    ┌────────────────────────────────┬──────────┬─────────────────┬─────────┐
    │             Target             │   Type   │ Vulnerabilities │ Secrets │
    ├────────────────────────────────┼──────────┼─────────────────┼─────────┤
    │ lab-secure:1.0.0 (debian 13.8) │  debian  │        0        │    -    │
    ├────────────────────────────────┼──────────┼─────────────────┼─────────┤
    │ app/server                     │ gobinary │        0        │    -    │
    └────────────────────────────────┴──────────┴─────────────────┴─────────┘
    Check:

    Six OS packages and one binary, with no HIGH or CRITICAL findings. New CVEs appear over time, so your result may differ.

  11. 11See what a failing gate looks like

    --exit-code 1 makes Trivy fail the build when it finds something at the given severity. This run used an nginx:1.29-alpine image that had sat unrefreshed on a machine for months — exactly the "it was fine when we built it" problem. A freshly pulled image may pass.

    Run
    docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v lab-trivy-cache:/root/.cache/ aquasec/trivy:0.76.2 image --severity CRITICAL --exit-code 1 --no-progress --scanners vuln --quiet nginx:1.29-alpine
    echo "trivy exit status: $?"
    

    Expected output

    ...
    │ nginx:1.29-alpine (alpine 3.23.4) │ alpine │        1        │
    ...
    Total: 1 (CRITICAL: 1)
    ...
    │ brotli-libs │ CVE-2026-111497 │ CRITICAL │ fixed  │ 1.2.0-r0          │ 1.2.1-r0      │ brotli: Out-of-Bounds Write in Google Brotli Decoder │
    ...
    trivy exit status: 1
    Check:

    A non-zero exit status is what stops a CI pipeline.

  12. 12Generate an SBOM

    A software bill of materials lists every package in the image. When the next big CVE is announced, you search SBOMs instead of rebuilding everything to find out whether you're affected.

    Run
    docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v lab-trivy-cache:/root/.cache/ aquasec/trivy:0.76.2 image --format cyclonedx --quiet lab-secure:1.0.0 > sbom.cdx.json
    jq -r '.bomFormat + " " + .specVersion' sbom.cdx.json
    jq -r '.components[] | "\(.type)\t\(.name)\t\(.version)"' sbom.cdx.json | sort | column -t
    

    Expected output

    CycloneDX 1.7
    application       app/server              null
    library           base-files              13.8+deb13u8
    library           ca-certificates         20250419+deb13u1
    library           example.com/secure-api  null
    library           media-types             13.0.0
    library           netbase                 6.5
    library           stdlib                  v1.26.11
    library           tzdata                  2026f-0+deb13u1
    library           tzdata-legacy           2026f-0+deb13u1
    operating-system  debian                  13.8
    Check:

    The whole runtime image is ten components — compare that with any general-purpose base image.

  13. 13Declare the same hardening in Compose

    Flags typed on a command line get forgotten; the same settings in a file get reviewed.

    compose.yaml
    services:
      api:
        image: secure-api:1.0.0
        build:
          context: .
          args:
            VERSION: 1.0.0
        ports:
          - "8080:8080"
        read_only: true
        tmpfs:
          - /tmp:rw,size=16m
        cap_drop:
          - ALL
        security_opt:
          - no-new-privileges:true
        mem_limit: 64m
        pids_limit: 100
        restart: unless-stopped
    
  14. 14Build, scan and push in CI

    On every pull request the workflow builds and scans. On main and on version tags (v1.0.0) it also pushes to GitHub Container Registry with semver, SHA and branch tags, provenance and an SBOM. The build cache lives in GitHub Actions, so CI builds stay fast. This workflow passes actionlint.

    .github/workflows/image.yml
    name: image
    
    on:
      pull_request:
      push:
        branches: [main]
        tags: ["v*.*.*"]
    
    permissions:
      contents: read
      packages: write
    
    env:
      IMAGE: ghcr.io/${{ github.repository }}
    
    jobs:
      build-scan-push:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v7
    
          - uses: docker/setup-buildx-action@v4
    
          - id: meta
            uses: docker/metadata-action@v6
            with:
              images: ${{ env.IMAGE }}
              tags: |
                type=semver,pattern={{version}}
                type=semver,pattern={{major}}.{{minor}}
                type=sha,prefix=sha-
                type=ref,event=branch
    
          # Build once, load it locally, and scan it before anything is pushed.
          - uses: docker/build-push-action@v7
            with:
              context: .
              load: true
              tags: secure-api:ci
              build-args: VERSION=${{ steps.meta.outputs.version }}
              cache-from: type=gha
              cache-to: type=gha,mode=max
    
          - uses: aquasecurity/[email protected]
            with:
              image-ref: secure-api:ci
              severity: CRITICAL,HIGH
              ignore-unfixed: true
              exit-code: "1"
    
          - if: github.event_name != 'pull_request'
            uses: docker/login-action@v4
            with:
              registry: ghcr.io
              username: ${{ github.actor }}
              password: ${{ secrets.GITHUB_TOKEN }}
    
          # Same inputs and cache as the scanned build, so this is a fast rebuild of the same image.
          - if: github.event_name != 'pull_request'
            uses: docker/build-push-action@v7
            with:
              context: .
              push: true
              tags: ${{ steps.meta.outputs.tags }}
              labels: ${{ steps.meta.outputs.labels }}
              build-args: VERSION=${{ steps.meta.outputs.version }}
              cache-from: type=gha
              provenance: mode=max
              sbom: true
    
    Check:

    After pushing a v1.0.0 tag, the package page on GitHub shows tags 1.0.0, 1.0 and sha-….

Clean up

docker rm -f lab-secure
docker image rm lab-secure:1.0.0 lab-secure:sha-$GIT_SHA
docker volume rm lab-trivy-cache
rm sbom.cdx.json

If you pushed to GitHub Container Registry, delete the package under your profile's Packages tab, or keep it private.

In production

This lab is the production setup for an image. What remains is policy: who may push, which images may run, and how fast you react when a new vulnerability lands in something you already shipped.

What changes

In this lab In production
Digests pinned by hand Renovate or Dependabot opens PRs when base images change; CI rebuilds and rescans
Trivy run once Scans on every build and scheduled rescans of images already running (new CVEs appear daily)
Image tags 1.0.0 and sha-… Immutable tags in the registry; deployments reference the digest
SBOM written to a file SBOM and provenance attached to the image in the registry (sbom: true, provenance: mode=max)
Images trusted because you built them Signed images (cosign / Sigstore) and an admission policy that only runs signed images from your registry
--read-only, --cap-drop ALL on the command line The same in Compose, ECS task definitions (readonlyRootFilesystem) or Kubernetes securityContext, enforced by policy

Defence in depth

No single setting is enough. Distroless removes the tools an attacker would use; non-root limits what a compromised process can do; a read-only filesystem stops it writing tools in; dropped capabilities and no-new-privileges stop it gaining more; limits stop it exhausting the host; scanning and SBOMs tell you when a dependency becomes dangerous.

Production checklist

  • Base images pinned by digest and updated by an automated, reviewed process
  • Runtime image contains only the application (distroless or scratch where possible)
  • Runs as a non-root numeric UID; root filesystem read-only; capabilities dropped; no-new-privileges set
  • Health check works without a shell
  • CI fails on HIGH/CRITICAL fixable vulnerabilities before anything is pushed
  • Running images are rescanned on a schedule, with alerts to the owning team
  • Every image carries version, commit and source labels; SBOM and provenance are attached
  • Registry tags are immutable; production deploys by digest
  • Images are signed and only signed images may run in production

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake