Dockerfile Deep Dive: Building Small, Fast and Secure Images

DevOps Certification 24 min min read Updated: Nov 17, 2026 Intermediate
Dockerfile Deep Dive: Building Small, Fast and Secure Images
Intermediate Topic 2 of 4

Dockerfile Instructions

InstructionPurpose
FROMBase image to start from
WORKDIRSet the working folder inside the image
COPYCopy files from your project into the image
RUNRun a command at build time (install packages)
ENVSet environment variables that stay in the image
ARGBuild-time variable only
EXPOSEDocuments the port the app listens on
USERSwitch to a non-root user
CMDDefault command when the container starts
ENTRYPOINTFixed executable; CMD becomes its default arguments
HEALTHCHECKCommand Docker runs to check the app is healthy

A First Dockerfile (Python)

dockerfile FROM python:3.13-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "app.py"]
bash docker build -t shop-api:1.0 . docker run -d -p 8000:8000 --name api shop-api:1.0

Layer Caching: Order Matters

Docker reuses a cached layer if the instruction and everything before it are unchanged. Put things that change rarely first (dependencies) and things that change often last (source code).

text Good order Bad order COPY requirements.txt . COPY . . <- any code change breaks the cache RUN pip install ... RUN pip install ... <- reinstall on every build COPY . .

.dockerignore

Exclude files that should never go into the build context: faster builds, smaller images and no leaked secrets.

text .git node_modules __pycache__ *.log .env Dockerfile docker-compose*.yml tests/ .terraform

CMD vs ENTRYPOINT

dockerfile # Exec form (JSON array) is preferred: no shell, signals reach your app CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"] # ENTRYPOINT + CMD: fixed program with default arguments ENTRYPOINT ["python", "tool.py"] CMD ["--help"] # docker run image --version -> runs: python tool.py --versio
Signals: Use the exec form ["cmd", "arg"]. With the shell form CMD cmd arg, Docker wraps your app in /bin/sh -c, and docker stop may not reach it, causing slow 10-second shutdowns.

Multi-Stage Builds

Compilers and build tools are needed to build, but not to run. A multi-stage Dockerfile uses one stage to build and a second, tiny stage to run. Only the final stage is shipped.

Node.js example

dockerfile # ---- build stage ---- FROM node:22-alpine AS build WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build # ---- runtime stage ---- FROM node:22-alpine WORKDIR /app ENV NODE_ENV=production COPY package*.json ./ RUN npm ci --omit=dev && npm cache clean --force COPY --from=build /app/dist ./dist USER node EXPOSE 3000 CMD ["node", "dist/server.js"]

Java example

dockerfile FROM maven:3-eclipse-temurin-21 AS build WORKDIR /src COPY pom.xml . RUN mvn -q dependency:go-offline COPY src ./src RUN mvn -q package -DskipTests FROM eclipse-temurin:21-jre WORKDIR /app COPY --from=build /src/target/app.jar app.jar USER 1001 EXPOSE 8080 ENTRYPOINT ["java", "-jar", "app.jar"]

Go example (tiny final image)

dockerfile FROM golang:1.24 AS build WORKDIR /src COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server FROM gcr.io/distroless/static-debian12 COPY --from=build /out/server /server USER nonroot ENTRYPOINT ["/server"]
Result

A Go app can shrink from over 800 MB (build image) to about 10 to 20 MB (distroless final image).

Security Best Practices

  • Run as a non-root user (USER)
  • Use small trusted bases: -slim, alpine, distroless, or hardened images
  • Pin versions and, for strict reproducibility, digests: FROM python:3.13-slim@sha256:...
  • Never put secrets in ENV, ARG or COPY. They remain in image layers
  • Scan images (Trivy, Docker Scout) in CI
  • Keep images updated and rebuild regularly for security patches
  • Use read-only root filesystem and drop capabilities at runtime when possible
dockerfile RUN addgroup --system app && adduser --system --ingroup app app USER app

Passing Secrets at Build Time Safely

dockerfile # syntax=docker/dockerfile:1 FROM alpine RUN --mount=type=secret,id=npmtoken \ NPM_TOKEN=$(cat /run/secrets/npmtoken) && echo "use token here, it is not saved in a layer"
bash docker build --secret id=npmtoken,src=./npm_token.txt -t demo .

BuildKit Cache Mounts

dockerfile # syntax=docker/dockerfile:1 FROM python:3.13-slim WORKDIR /app COPY requirements.txt . RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt

BuildKit is the default builder in current Docker. It builds stages in parallel and supports secrets, cache mounts and multi-platform builds.

bash docker buildx build --platform linux/amd64,linux/arm64 -t myrepo/shop-api:1.0 --push .

Healthcheck

dockerfile HEALTHCHECK --interval=30s --timeout=3s --retries=3 \ CMD curl -f http://localhost:8000/health || exit 1
bash docker ps # STATUS shows (healthy) or (unhealthy)

In Kubernetes you use liveness and readiness probes instead, but a Docker healthcheck is useful with Compose and plain Docker.

Checking Image Size

bash docker images shop-api docker history shop-api:1.0 # explore layers interactively (tool called dive) dive shop-api:1.0
TechniqueEffect
Multi-stage buildRemoves compilers and build tools
Slim or distroless baseRemoves shell, package manager and many CVEs
Combine RUN commands and clean cachesapt-get update && apt-get install -y x && rm -rf /var/lib/apt/lists/*
.dockerignoreSmaller context and faster builds
npm ci --omit=dev or pip --no-cache-dirSkips dev dependencies and caches

Practice Tasks

  1. Containerize a small Flask or Express app and measure build time before and after reordering COPY
  2. Convert it to a multi-stage build and compare image sizes
  3. Make it run as non-root and prove it with docker exec ... id
  4. Add a .dockerignore and a healthcheck
  5. Build a multi-platform image with buildx

Conclusion

A good Dockerfile is ordered for cache hits, built in stages, runs as a non-root user and ships only what is needed to run. Small images start faster, cost less and have fewer vulnerabilities.

Quick Summary: cache order; .dockerignore; exec-form CMD; multi-stage; non-root; no secrets in layers; buildx.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators