पाठ 19 / 31
Building Hardened Container Images
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Write Dockerfiles that use minimal base images, multi-stage builds and a non-root user.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
Less inside means less to attack
A container image is a bundle of your app plus an operating-system userland. Every extra package is extra attack surface and extra CVEs for scanners to report. Hardening starts with the base image: choose a small, maintained one such as a slim distribution image, Alpine, or a distroless image that contains only the runtime and no shell or package manager. Use multi-stage builds: compile in a full build image, then copy only the output into a minimal runtime stage, so compilers and build tools never ship. Run as a non-root user; if an attacker gets code execution, root inside the container makes container escapes and host damage easier. Pin base images by digest for reproducibility and let a bot update them. Never put secrets in build arguments or layers, add a .dockerignore, and set a read-only root filesystem at runtime where the app allows it.
From Dockerfile to running container
Hardening happens at four points: a minimal Dockerfile, a scanned image, a checked infrastructure definition, and a locked-down runtime configuration.
A multi-stage, non-root Go image
The final image has the static binary and almost nothing else. The nonroot variant of the distroless image runs as an unprivileged user.
# syntax=docker/dockerfile:1
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/api"]No shell is a feature
Distroless images have no shell, which surprises people debugging with docker exec. Use ephemeral debug containers (kubectl debug) instead of adding a shell back to production images.
त्वरित जाँच: What is the main security benefit of a multi-stage Docker build?
- It encrypts the image layers
- It lets the container run as root safely
- It makes the image pull from multiple registries
- Build tools and source code stay in the build stage and are not shipped in the final image
Answer
Build tools and source code stay in the build stage and are not shipped in the final image — Only the copied artefacts reach the final stage, reducing size and attack surface.