Images & Registries
Build efficient images, tag them well, and push/pull from registries.
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:
alpineordistrolessshrink 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.
# 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 - Explain why Dockerfile instruction order affects build cache.
- Convert a single-stage Dockerfile to multi-stage and compare image sizes.
- Add a
.dockerignoreand list two things it should exclude. - Tag an image with a semantic version and push it to a registry.
Cheat Sheet▾
| Task | Command |
|---|---|
| Build + tag | docker build -t name:tag . |
| List images | docker images |
| Tag existing | docker tag src name:tag |
| Push / pull | docker push / docker pull |
| Inspect layers | docker history image |
| Login to registry | docker 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.