Images & Registries

💤0
Lv 10 XP
← 📦 Containers & Kubernetes · Docker

Images & Registries

Intermediate ⭐ 80 XP ⏱ 18 min #docker#images#registry

Build efficient images, tag them well, and push/pull from registries.

📖Theory

A Docker image is built in layers — each Dockerfile instruction adds one, and layers are cached and shared between images. Smaller, fewer layers mean faster builds and pulls. Key techniques:

  • Order for cache: copy dependency manifests and install before copying source
  • Multi-stage builds: compile in one stage, copy only artifacts to a slim final image
  • Small base images: alpine or distroless shrink size and attack surface
  • .dockerignore: keep junk (node_modules, .git) out of the build context

A registry stores and distributes images (Docker Hub, GHCR, ECR/ACR/GCR). You tag images name:tag and push/pull them. Use immutable, versioned tags — avoid relying on latest in production.

🌍Real-World Example
# Multi-stage build → small final image
FROM golang:1.22 AS build
WORKDIR /src
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app

FROM gcr.io/distroless/static
COPY --from=build /app /app
ENTRYPOINT ["/app"]
docker build -t ghcr.io/me/app:1.0.0 .
docker push ghcr.io/me/app:1.0.0
docker images        # compare sizes
✍️Hands-On Exercise
  1. Explain why Dockerfile instruction order affects build cache.
  2. Convert a single-stage Dockerfile to multi-stage and compare image sizes.
  3. Add a .dockerignore and list two things it should exclude.
  4. Tag an image with a semantic version and push it to a registry.
🧾Cheat Sheet
TaskCommand
Build + tagdocker build -t name:tag .
List imagesdocker images
Tag existingdocker tag src name:tag
Push / pulldocker push / docker pull
Inspect layersdocker history image
Login to registrydocker login registry
Ignore files.dockerignore
💬Common Interview Questions
Why does Dockerfile instruction order matter?

Each instruction is a cached layer; a change invalidates that layer and all after it. Copying dependency manifests and installing before source keeps the expensive install step cached when only code changes.

What is a multi-stage build and why use it?

It uses multiple FROM stages — building in one and copying only the artifacts into a minimal final image — producing smaller, more secure images without build tools.

Why avoid relying on the latest tag in production?

latest is just a default label, not guaranteed to be a specific version. Pinning explicit versions makes deployments reproducible and rollbacks reliable.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type