Assignments
25 practical assignments: 10 ๐ข Beginner, 10 ๐ก Intermediate, 5 ๐ด Advanced. Do them on a real machine; reading is not enough.
Index
| # | Level | Assignment |
|---|---|---|
| 1 | ๐ข | Run your first containers |
| 2 | ๐ข | Images, layers and inspection |
| 3 | ๐ข | Your first Dockerfile |
| 4 | ๐ข | Port publishing and environment variables |
| 5 | ๐ข | Volumes vs bind mounts |
| 6 | ๐ข | .dockerignore and the build context |
| 7 | ๐ข | CMD vs ENTRYPOINT |
| 8 | ๐ข | User-defined networks and DNS |
| 9 | ๐ข | Your first Compose file |
| 10 | ๐ข | Tag and push to a registry |
| 11 | ๐ก | Multi-stage build and image size |
| 12 | ๐ก | Layer cache optimization |
| 13 | ๐ก | Non-root and read-only containers |
| 14 | ๐ก | Healthchecks and health-gated startup |
| 15 | ๐ก | Compose env files, profiles and overrides |
| 16 | ๐ก | Resource limits and the OOM killer |
| 17 | ๐ก | Scan and fix with Trivy |
| 18 | ๐ก | Back up and restore a database volume |
| 19 | ๐ก | Debug a crash-looping container |
| 20 | ๐ก | BuildKit cache and secret mounts |
| 21 | ๐ด | Multi-architecture images with buildx |
| 22 | ๐ด | Distroless and scratch images |
| 23 | ๐ด | Build a container by hand with namespaces and cgroups |
| 24 | ๐ด | CI pipeline: build, scan, sign, SBOM, push |
| 25 | ๐ด | Private registry with TLS, auth and promotion by digest |
๐ข Beginner
Assignment 1. Run your first containers ๐ข
Objective: Get comfortable with the container lifecycle commands.
Tasks
- Run
nginx:alpinedetached, namedweb1, with host port 8081 mapped to container port 80. - Fetch the page with
curl, then read the container's logs. - Open a shell inside it with
docker execand list/usr/share/nginx/html. - Stop it, list all containers including stopped ones, restart it, then remove it.
- Run
alpine echo hellowith--rmand confirm no container is left behind.
Expected outcome / acceptance criteria
curl localhost:8081returns the nginx welcome page.docker ps -ashows no leftover containers after step 5.- You can explain the difference between
stop,killandrm.
Hints
docker run -d --name web1 -p 8081:80 nginx:alpine, docker logs web1, docker exec -it web1 sh, docker ps -a. --rm deletes the container when the process exits.
Bonus: Run docker stats --no-stream and docker top web1; identify the PID of the nginx master process on the host using docker inspect -f '{{.State.Pid}}' web1.
Assignment 2. Images, layers and inspection ๐ข
Objective: Understand that an image is a stack of layers plus metadata.
Tasks
- Pull
alpine:3.20,python:3.12-slim, andpython:3.12; compare sizes. - Run
docker historyon each and identify the largest layer. - Use
docker inspectto find the defaultCmd,Env, andArchitectureofpython:3.12-slim. - Pull the same image by digest (get it from
docker images --digests). - Delete the images and note which layers were shared.
Expected outcome / acceptance criteria
- A short note with the three sizes and the reason for the difference (base OS packages and toolchains).
- You can pull by digest and explain why a digest is immutable but a tag is not.
Hints
docker images --digests, docker history --no-trunc, docker inspect --format '{{json .Config}}' python:3.12-slim | jq. Pull by digest: docker pull python@sha256:<digest>.
Bonus: Install dive and explore python:3.12 layer by layer; list the three biggest files.
Assignment 3. Your first Dockerfile ๐ข
Objective: Package a static site into an image.
Tasks
- Create
index.htmlwith any content. - Write a Dockerfile
FROM nginx:alpinethat copies it to/usr/share/nginx/html/. - Build it as
mysite:1.0and run it on port 8082. - Change the HTML, rebuild as
mysite:1.1, and watch which layers are rebuilt versus cached. - Run both versions side by side on ports 8082 and 8083.
Expected outcome / acceptance criteria
- Two images, two running containers, different content.
- Build output shows
CACHEDfor the base layer on the second build.
Hints
FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.htmldocker build -t mysite:1.0 .
Bonus: Add LABEL org.opencontainers.image.authors and view it with docker inspect.
Assignment 4. Port publishing and environment variables ๐ข
Objective: Configure containers at runtime without rebuilding.
Tasks
- Run
postgres:16-alpinewithPOSTGRES_PASSWORDset via-e, without publishing a port. Try connecting from the host and observe the failure. - Re-run publishing
127.0.0.1:5433:5432and connect withpsql(ordocker exec ... psql). - Run
docker run --rm -e GREETING=hi alpine sh -c 'echo $GREETING'. - Move the variables into an env file and use
--env-file. - Run the container with
-Pand find which random host port was assigned.
Expected outcome / acceptance criteria
- Connection fails without
-p, succeeds with it, and is bound only to localhost. - You can explain
0.0.0.0:5433vs127.0.0.1:5433and why the second is safer.
Hints
docker port <name> shows mappings. --env-file ./db.env takes KEY=value lines without quotes or export.
Bonus: Inspect iptables -t nat -L DOCKER -n and find the DNAT rule created for your published port.
Assignment 5. Volumes vs bind mounts ๐ข
Objective: Prove which storage type survives container deletion.
Tasks
- Run a container that writes a file to
/datawith no volume. Remove it, run a new one, and confirm the file is gone. - Repeat with a named volume
mydataand confirm the file survives. - Repeat with a bind mount of
$(pwd)/hostdataand compare file ownership on the host. - Inspect the volume and locate its mountpoint.
- Mount a bind mount as read-only (
:ro) and show that writes fail.
Expected outcome / acceptance criteria
- A table of the three cases with "persists? yes/no" and who owns the files.
touch: ... Read-only file systemobserved for the:romount.
Hints
docker run --rm -v mydata:/data alpine sh -c 'echo hi > /data/f'; docker volume inspect mydata; -v "$PWD/hostdata:/data:ro" or --mount type=bind,src=...,dst=/data,readonly.
Bonus: Use a tmpfs mount and verify that data disappears when the container stops.
Assignment 6. .dockerignore and the build context ๐ข
Objective: See how the build context affects speed and security.
Tasks
- Create a project directory containing a 200 MB dummy file (
dd if=/dev/zero of=big.bin bs=1M count=200) and a fake.envwith a secret. - Build with a Dockerfile that only copies
app.txtand note the "transferring context" size. - Add a
.dockerignoreexcludingbig.bin,.env,.git, and rebuild. - Write a Dockerfile with
COPY . .first without.dockerignore, then verify the secret is inside the image.
Expected outcome / acceptance criteria
- Context size drops from about 200 MB to a few KB.
- You demonstrate
docker run --rm img cat /app/.envleaking the secret, then show the fix.
Hints
Build with --progress=plain to see context transfer. .dockerignore patterns are relative to the context root.
Bonus: Use docker build --no-cache --progress=plain and explain why even a deleted secret in an earlier layer is still extractable.
Assignment 7. CMD vs ENTRYPOINT ๐ข
Objective: Predict exactly what runs for each combination.
Tasks
- Build three images that print their arguments: only
CMD ["echo","default"]; onlyENTRYPOINT ["echo"]; bothENTRYPOINT ["echo"]andCMD ["default"]. - Run each with no arguments and with
extra args. - Create a fourth image using shell form (
CMD echo $HOME) and show it runs through/bin/sh -c. - Override the entrypoint at runtime with
--entrypoint sh.
Expected outcome / acceptance criteria
- A 3x2 table of outputs that you predicted before running.
- You can explain why exec form is required for signal handling.
Hints
docker run img extra args replaces CMD and is appended to ENTRYPOINT. In shell form PID 1 is sh, check with docker exec c ps.
Bonus: Show that docker stop takes 10 seconds with a shell-form sleep command and returns instantly with exec form plus a trap or --init.
Assignment 8. User-defined networks and DNS ๐ข
Objective: Show service discovery by name.
Tasks
- Start two containers on the default bridge and try
pingby name. Observe failure. - Create
docker network create appnet, start the same two containers on it, and ping by name. - Run
nginxonappnetandcurl http://<name>from a second container. - Inspect the network to see subnet and attached containers.
- Attach a running container to a second network with
docker network connect.
Expected outcome / acceptance criteria
- Default bridge:
ping: bad address; user-defined network: replies. - You can state where the embedded DNS lives (
127.0.0.11) and why it needs a user-defined network.
Hints
docker run -dit --name a --network appnet alpine sh, docker exec a ping -c1 b, docker network inspect appnet, cat /etc/resolv.conf in the container.
Bonus: Create a network with --internal and prove containers on it cannot reach the internet.
Assignment 9. Your first Compose file ๐ข
Objective: Describe a two-service app declaratively.
Tasks
- Write
compose.yamlwithweb(nginx, port 8080) andcache(redis:7-alpine). - Run
docker compose up -dand verify withdocker compose ps. - From
web, resolvecacheby name. - View logs with
docker compose logs -f cache. - Tear down with
docker compose downand confirm networks and containers are gone.
Expected outcome / acceptance criteria
- One command brings both up and one command removes both.
docker compose exec web ping -c1 cacheworks.
Hints
Compose creates a default network named <project>_default. Run docker compose config to see the resolved file.
Bonus: Add a named volume to redis and prove that data survives down but not down -v.
Assignment 10. Tag and push to a registry ๐ข
Objective: Publish an image with a sensible tag scheme.
Tasks
- Create a free account on Docker Hub or GHCR and log in with an access token (not your password).
- Tag
mysite:1.0as<registry>/<user>/mysite:1.0and:1. - Push both tags and verify them on the registry website.
- Remove local images, pull from the registry, and run it.
- Explain why you should not rely on
:latest.
Expected outcome / acceptance criteria
- Both tags visible on the registry and both resolve to the same digest.
- A pull on a clean machine (or after
docker rmi) runs the app.
Hints
echo $TOKEN | docker login -u USER --password-stdin, docker tag src dst, docker push dst. GHCR needs lowercase names.
Bonus: Make the repository private and show the pull access denied error when logged out.
๐ก Intermediate
Assignment 11. Multi-stage build and image size ๐ก
Objective: Cut an image by at least 80% without changing behaviour.
Tasks
- Write a small Go (or Node/Python) HTTP service with a single-stage Dockerfile on
golang:1.23(or the full language image) and record the size. - Convert it to a multi-stage build that copies only the binary (or production dependencies) into a minimal runtime stage.
- Record the new size and run both to prove identical responses.
- Add
--targetbuilds: ateststage that runs unit tests and aruntimestage.
Expected outcome / acceptance criteria
- Final image at least 80% smaller (for Go: under 20 MB on alpine).
docker build --target test .runs tests; the default build does not include test files.
Hints
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
FROM alpine:3.20
COPY --from=build /out/app /app
USER 10001
ENTRYPOINT ["/app"]Bonus: Add a third stage FROM scratch and compare size and debuggability.
Assignment 12. Layer cache optimization ๐ก
Objective: Make rebuilds after a code change take seconds.
Tasks
- Take a Node or Python app whose Dockerfile does
COPY . .before installing dependencies. Time a rebuild after editing one source file. - Reorder: copy the dependency manifest first, install, then copy the source. Time it again.
- Use
RUN --mount=type=cachefor the package manager cache. - Find a
RUN apt-get updatefollowed by a separateRUN apt-get installand merge them correctly, cleaning lists in the same layer.
Expected outcome / acceptance criteria
- Before/after timings recorded; the post-edit rebuild skips the dependency install.
- You can explain why
apt-get updatealone in a layer causes stale package indexes.
Hints
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Use docker build --progress=plain to see CACHED markers.
Bonus: Add --cache-from/--cache-to type=registry and show a cold CI-like build reusing remote cache.
Assignment 13. Non-root and read-only containers ๐ก
Objective: Apply the container hardening baseline to a real image.
Tasks
- Show that a default
python:3.12-slimcontainer runs as root (id). - Create a dedicated user (
adduser/useraddwith a fixed UID such as 10001) and setUSERin the Dockerfile; fix file ownership withCOPY --chown. - Run with
--read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges. - Make the app listen on a port above 1024 and confirm it works without
NET_BIND_SERVICE. - Demonstrate that writing outside
/tmpfails.
Expected outcome / acceptance criteria
docker exec c idreturns a non-zero UID.- The app serves traffic under all hardening flags;
docker inspectshowsReadonlyRootfs: trueandCapDrop: [ALL].
Hints
On Alpine: addgroup -S app -g 10001 && adduser -S app -u 10001 -G app. Debian: useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin app. If the app needs a writable cache directory, point it to /tmp via an env var.
Bonus: Run the same container on Kubernetes-style settings: --user 12345:12345 with an arbitrary UID and make it still work.
Assignment 14. Healthchecks and health-gated startup ๐ก
Objective: Make startup order depend on actual readiness.
Tasks
- Write a Compose stack with
postgres:16-alpineand an app that connects to it. - Add a
pg_isreadyhealthcheck on the database and an HTTP healthcheck on the app. - Use
depends_on: condition: service_healthy. - Compare with plain
depends_onby addingsleepto the DB entrypoint and observing the app crash. - Break the app's health endpoint and watch the status change to
unhealthyindocker ps.
Expected outcome / acceptance criteria
- With health-gating, the app starts only after the database reports
healthy. docker inspect --format '{{json .State.Health}}'shows the failing log entries.
Hints
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"]; use start_period so slow boots do not count as failures. Healthchecks do not restart containers by themselves in plain Docker.
Bonus: Add restart: unless-stopped plus a small "autoheal" sidecar, or explain why Kubernetes liveness probes replace this.
Assignment 15. Compose env files, profiles and overrides ๐ก
Objective: Run one codebase in dev and prod modes cleanly.
Tasks
- Create
compose.yaml(base),compose.override.yaml(dev: bind-mount source, debug ports) andcompose.prod.yaml(no bind mounts, restart policies, resource limits). - Use
.envfor interpolation andenv_filefor container variables; show the difference. - Add an
adminerservice underprofiles: ["debug"]. - Run
docker compose up -d,docker compose --profile debug up -d, anddocker compose -f compose.yaml -f compose.prod.yaml up -d. - Use
docker compose configto prove the merged result.
Expected outcome / acceptance criteria
adminerstarts only with the profile; prod config contains no bind mounts.- A required variable uses
${VAR:?message}and fails fast when missing.
Hints
docker compose automatically merges compose.override.yaml. With -f, you must list every file yourself. Lists such as ports are appended on merge; use !reset (Compose 2.24+) to clear them.
Bonus: Use Compose secrets: with a file source and read it from /run/secrets/<name>.
Assignment 16. Resource limits and the OOM killer ๐ก
Objective: See memory and CPU limits enforced.
Tasks
- Run a container with
--memory 64m --memory-swap 64mthat allocates memory in a loop (for examplepython -c "a=[]\nwhile True: a.append(bytearray(10**6))"). - Confirm exit code 137 and
OOMKilled: true. - Run a CPU burner with
--cpus 0.5and verify viadocker statsthat it stays near 50%. - Set
--pids-limit 50and run a fork bomb-like loop safely inside the container. - Read the matching cgroup files on the host.
Expected outcome / acceptance criteria
docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}}'printstrue 137.- You can explain why limits matter for noisy neighbours and why JVM/Node need to be told about the limit.
Hints
cgroup v2 files: /sys/fs/cgroup/system.slice/docker-<id>.scope/memory.max and cpu.max. dmesg | grep -i 'killed process' shows the kernel message.
Bonus: Run a Node app with --max-old-space-size set to 75% of the container limit and compare behaviour.
Assignment 17. Scan and fix with Trivy ๐ก
Objective: Reduce real vulnerabilities, not just collect reports.
Tasks
- Scan
node:18(or another old image) withtrivy image --severity HIGH,CRITICAL. - Scan your own multi-stage image from the lab and compare counts.
- Fix at least five findings by changing base image, bumping dependencies, or removing packages.
- Run
trivy configon your Dockerfile and Compose file and fix at least two misconfigurations. - Add
--exit-code 1 --ignore-unfixedto produce a CI-style gate and a.trivyignoreentry with a reason and date.
Expected outcome / acceptance criteria
- A before/after table of finding counts per severity.
- Gate command exits 0 on the fixed image and 1 on the old image.
Hints
trivy image --format table --severity HIGH,CRITICAL <img>, trivy image --scanners vuln,secret,misconfig <img>. Prefer -slim/alpine/distroless bases, and rebuild with --pull.
Bonus: Generate a CycloneDX SBOM and query it with jq for a specific package.
Assignment 18. Back up and restore a database volume ๐ก
Objective: Prove you can recover a stateful container.
Tasks
- Start Postgres with a named volume and insert sample data.
- Make a logical backup with
pg_dumpand a physical copy of the volume using a throwawaytarcontainer. - Delete the container and volume, create a new volume, and restore from each backup.
- Verify row counts match.
- Document the recovery steps in a short runbook.
Expected outcome / acceptance criteria
- Data restored byte for byte (row counts and a checksum query).
- Runbook lists commands, expected duration, and when to prefer logical vs physical backups.
Hints
docker exec db pg_dump -U shack -Fc shackdb > backup.dump
docker run --rm -v pgdata:/data -v "$PWD":/backup alpine tar czf /backup/pgdata.tgz -C /data .Physical copy of a running database may be inconsistent; stop the container or use pg_basebackup. Restore logical with pg_restore -U shack -d shackdb --clean backup.dump.
Bonus: Schedule the logical backup with a Compose service on a cron-like loop and ship it to S3-compatible storage (MinIO).
Assignment 19. Debug a crash-looping container ๐ก
Objective: Diagnose from symptoms using only Docker tooling.
Tasks
- Start the broken stack below and find out why
apikeeps restarting, without reading the source first. - Find the exit code, last logs, and the exact failing command.
- Fix it and write a 3-line root-cause summary.
- Repeat for two more failures you introduce yourself: wrong
CMDpath, and a missing environment variable.
services:
api:
image: node:22-alpine
command: ["node", "/app/server.js"]
restart: always
environment:
DB_HOST: databaseExpected outcome / acceptance criteria
- You identify
Cannot find module '/app/server.js'(exit 1) withdocker logsanddocker inspect. - Three distinct failure types diagnosed, each with the commands you used.
Hints
docker ps -a, docker logs --tail 50 <c>, docker inspect -f '{{.State.ExitCode}} {{.State.Error}} {{.RestartCount}}' <c>, docker events --since 5m. To poke around a crashing container: docker run --rm -it --entrypoint sh <image>.
Bonus: Explain exit codes 0, 1, 125, 126, 127, 137, 139, 143.
Assignment 20. BuildKit cache and secret mounts ๐ก
Objective: Use credentials during a build without leaving them in the image.
Tasks
- Write a Dockerfile that installs a private-style dependency using a token with
ARG TOKENand show thatdocker historyexposes it. - Rewrite it with
RUN --mount=type=secret,id=npm_tokenand pass--secret id=npm_token,src=./token.txt. - Prove the secret is absent from
docker historyand from the filesystem of the final image. - Add
--mount=type=cachefor the package cache and compare rebuild times.
Expected outcome / acceptance criteria
docker history --no-truncleaks the token in version 1 and not in version 2.- Searching the image filesystem (
docker save | tar -xthengrep -r) finds nothing.
Hints
# syntax=docker/dockerfile:1.7
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN=$(cat /run/secrets/npm_token) npm ciSecret mounts are available only during that RUN and are not stored in layers.
Bonus: Use --mount=type=ssh with docker build --ssh default to clone a private Git repository.
๐ด Advanced
Assignment 21. Multi-architecture images with buildx ๐ด
Objective: Publish one tag that works on amd64 and arm64.
Tasks
- Create a buildx builder with the
docker-containerdriver. - Build and push
linux/amd64,linux/arm64for your app to a registry. - Inspect the manifest list and verify both platform entries.
- Run the arm64 variant on an amd64 host through QEMU (
tonistiigi/binfmt) and confirmuname -m. - Compare build time of emulated builds with cross-compilation using
--platform=$BUILDPLATFORMandTARGETARCHin a Go Dockerfile.
Expected outcome / acceptance criteria
docker buildx imagetools inspect <image>lists both architectures under one tag.- Cross-compiled build is measurably faster than emulation.
Hints
docker buildx create --name multi --driver docker-container --use
docker run --privileged --rm tonistiigi/binfmt --install all
docker buildx build --platform linux/amd64,linux/arm64 -t REG/app:1.0 --push .
docker run --rm --platform linux/arm64 REG/app:1.0 uname -mIn the Dockerfile: FROM --platform=$BUILDPLATFORM golang:1.23 AS build then GOOS=linux GOARCH=$TARGETARCH go build.
Bonus: Add registry-backed cache (--cache-to type=registry,mode=max) and measure the second build.
Assignment 22. Distroless and scratch images ๐ด
Objective: Ship the smallest runnable image and still be able to debug it.
Tasks
- Build a static Go binary (
CGO_ENABLED=0) and run it fromFROM scratch. Fix the missing CA certificates and timezone data problems you hit. - Build the same app on
gcr.io/distroless/static-debian12:nonrootand a Node app ongcr.io/distroless/nodejs22-debian12:nonroot. - Compare sizes and Trivy findings across alpine, distroless and scratch.
- Debug the distroless container using
docker debugor an ephemeralnicolaka/netshootsidecar sharing its namespaces. - Add a healthcheck without a shell or
curl(hint: the app binary gets a--healthcheckflag).
Expected outcome / acceptance criteria
- Scratch/distroless image under 15 MB for Go and runs as non-root.
- You can reach into the running container with a debug tool even though it has no shell.
Hints
Copy certs: COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/. For a numeric user in scratch: USER 10001:10001. Debug sidecar: docker run --rm -it --pid container:app --net container:app nicolaka/netshoot.
Bonus: Write a short decision guide: when would you not use scratch or distroless?
Assignment 23. Build a container by hand with namespaces and cgroups ๐ด
Objective: Demystify containers by creating one without Docker.
Tasks
- Export an Alpine root filesystem:
docker export $(docker create alpine) | tar -x -C rootfs. - Use
unsharewith PID, mount, UTS, IPC and network namespaces andchrootintorootfs; mount/proc. - Show that PID 1 inside differs from the host PID, and change the hostname without affecting the host.
- Create a cgroup v2 group, set
memory.maxto 50 MB andpids.maxto 20, put your shell into it, and trigger the limits. - Connect the network namespace to the host with a veth pair and a bridge or NAT rule so it can reach the internet.
Expected outcome / acceptance criteria
psinside shows only your processes;hostnamediffers from the host.- Exceeding
memory.maxkills the process;pids.maxmakesforkfail. - A short write-up mapping each step to the Docker feature it implements.
Hints
sudo unshare --pid --fork --mount --uts --ipc --net --mount-proc=rootfs/proc chroot rootfs /bin/sh
sudo mkdir /sys/fs/cgroup/demo
echo 50M | sudo tee /sys/fs/cgroup/demo/memory.max
echo $$ | sudo tee /sys/fs/cgroup/demo/cgroup.procsVeth: ip link add veth0 type veth peer name veth1, move one end with ip link set veth1 netns <pid>, then address, route and iptables -t nat -A POSTROUTING -s 10.200.0.0/24 -j MASQUERADE. Use pivot_root instead of chroot for the bonus.
Bonus: Add a user namespace (--user --map-root-user) and explain how rootless containers use it.
Assignment 24. CI pipeline: build, scan, sign, SBOM, push ๐ด
Objective: Produce a trustworthy, traceable image from every merge.
Tasks
- Create a GitHub Actions workflow that builds with
docker/build-push-action, usingdocker/metadata-actionto generate tags (semver on git tags,sha-<short>on every commit). - Run Trivy as a gate (
exit-code: 1,severity: HIGH,CRITICAL,ignore-unfixed: true) before the push. - Push to GHCR using the built-in
GITHUB_TOKENwith least-privilegepermissions. - Generate an SBOM and provenance attestation (
sbom: true,provenance: mode=max) and sign the image keylessly withcosign. - Verify the signature locally with
cosign verifyand fail a deployment script when verification fails.
Expected outcome / acceptance criteria
- A push of tag
v1.2.3creates1.2.3,1.2, andsha-xxxxxxxtags; a vulnerable base image makes the pipeline fail before push. cosign verifysucceeds with the expected certificate identity and issuer.
Hints
Permissions block: contents: read, packages: write, id-token: write (for keyless signing). Sign by digest, not tag: cosign sign --yes ghcr.io/org/app@${{ steps.build.outputs.digest }}. Verify with --certificate-identity-regexp and --certificate-oidc-issuer https://token.actions.githubusercontent.com. Cache with cache-from: type=gha and cache-to: type=gha,mode=max.
Bonus: Add a scheduled nightly workflow that re-scans the latest released image and opens an issue on new HIGH findings.
Assignment 25. Private registry with TLS, auth and promotion by digest ๐ด
Objective: Run and operate your own registry and promote images between environments safely.
Tasks
- Run
registry:2with TLS (self-signed CA or a real certificate) and htpasswd basic auth, storing data on a named volume. - Push an image tagged
dev-<sha>; log in from a second host or container that trusts your CA. - Implement promotion: after tests pass, retag the same digest as
staging, thenprod-1.0.0, withdocker buildx imagetools createorcrane copy, without rebuilding. - Prove that
stagingandprod-1.0.0have identical digests and that deployments reference the digest. - Enable deletion in the registry config, delete an old tag, and run garbage collection to reclaim space.
- Configure a pull-through cache (
proxy.remoteurl) for Docker Hub and setregistry-mirrorsindaemon.json.
Expected outcome / acceptance criteria
- Unauthenticated pull fails with
no basic auth credentials; authenticated pull works over HTTPS. - Digest equality demonstrated; disk usage drops after garbage collection.
Hints
htpasswd -Bbn user pass > auth/htpasswd. Env vars: REGISTRY_AUTH=htpasswd, REGISTRY_AUTH_HTPASSWD_REALM=Registry, REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd, REGISTRY_HTTP_TLS_CERTIFICATE, REGISTRY_HTTP_TLS_KEY, REGISTRY_STORAGE_DELETE_ENABLED=true. GC: docker exec registry registry garbage-collect /etc/docker/registry/config.yml. Trust the CA by placing it in /etc/docker/certs.d/<host:port>/ca.crt.
Bonus: Replace registry:2 with Harbor or an ECR/GAR repository and add tag immutability plus a lifecycle policy.