DockerIntermediate

Docker Best Practices: Building Efficient and Secure Containers

7 min read

TL;DR

Learn essential Docker best practices for building efficient, secure, and maintainable container images, including multi-stage builds, security scanning, and optimization techniques.

Docker Best Practices: Building Efficient and Secure Containers

Executive Summary

A production Docker image is judged on four things: how fast it builds, how small it is, how few known vulnerabilities it carries, and whether it behaves predictably under resource pressure. This guide walks through the practices that determine those outcomes: multi-stage builds that keep toolchains out of the runtime image, layer ordering that makes the build cache work for you, pinned and minimal base images, non-root execution, health checks, and explicit resource limits. After reading it, you should be able to take a typical development Dockerfile and turn it into one you would be comfortable shipping and maintaining.

Why This Matters

A careless Dockerfile creates costs that compound. Bloated images slow every pull, every deployment, and every autoscaling event, and they inflate registry storage across every environment. Unpinned base images mean the same source tree can produce a different image next month, which turns rollbacks into guesswork and incident response into archaeology. Images built without a non-root user or vulnerability scanning convert a single application bug into a host-level compromise and leave known CVEs sitting in production indefinitely. These are not theoretical risks; they are the most common findings in container security audits, and all of them are cheap to prevent at build time and expensive to fix later.

Core Concepts

Multi-Stage Builds

A multi-stage build separates compilation from execution. The build stage can contain compilers, dev dependencies, and source code; the final stage receives only the artifacts it needs to run. This shrinks the image and removes an entire class of attack surface, because tools that are not in the image cannot be abused inside it.

# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Production stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
EXPOSE 3000
CMD ["npm", "start"]

Note the ordering inside the build stage: the dependency manifest is copied and installed before the source code. Docker caches each layer, and a layer is only rebuilt when its inputs change. Source files change on almost every commit; package.json changes rarely. Copying manifests first means most builds reuse the cached dependency layer instead of reinstalling everything.

Minimal, Pinned Base Images

Prefer slim or Alpine variants of official images, and pin to a specific version rather than a floating tag such as latest. A pinned image is reproducible: the build you tested is the build you deploy. Smaller bases also carry fewer packages, which means fewer vulnerabilities for a scanner to report and fewer components to patch.

Run as a Non-Root User

By default, processes in a container run as root. Root inside a container is not identical to root on the host, but a container escape or a mounted Docker socket turns it into exactly that. Create a dedicated user in the image, give it ownership of only the files it needs, and switch to it before the entrypoint.

# Use specific version for reproducibility
FROM node:18.19.0-alpine3.18

# Add non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Set working directory and permissions
WORKDIR /app
COPY --chown=appuser:appgroup . .

# Install dependencies
RUN npm ci --only=production

# Use non-root user
USER appuser

# Define health check
HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

EXPOSE 3000
CMD ["npm", "start"]

Layer Hygiene and .dockerignore

Each RUN, COPY, and ADD instruction creates a layer. Two rules follow from that. First, clean up in the same layer that creates the mess: deleting a file in a later layer does not remove it from the image, it only hides it in the merged view. Second, keep the build context small. Everything in the context directory is sent to the builder, and anything you COPY . . without a .dockerignore can end up in the image, including .env files and credentials.

.git
node_modules
npm-debug.log
Dockerfile
.dockerignore
.env
*.md

Runtime Configuration: Limits, Logging, Health Checks

An image is only half the contract; the other half is how it is run. Set CPU and memory limits so one container cannot starve its neighbours, cap log size so a chatty service cannot fill the host disk, and define a health check that reflects real readiness rather than mere process existence.

version: '3.8'
services:
  app:
    image: myapp:latest
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 256M
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

Development Workflow

Use Compose targets to share one Dockerfile between development and production. A development target can mount the source tree for live reload while the production target stays immutable. The promotion path should be: build once in CI, scan the image, push it to a registry, and deploy that exact digest to staging and then production. Rebuilding at deploy time produces a different artifact from the one you tested.

Decision Framework

SituationRecommendation
Compiled or bundled applicationMulti-stage build; ship only the runtime artifact
Image scan reports many OS-level CVEsMove to a slim, Alpine, or distroless base and rebuild on a schedule
Builds are slow in CIReorder layers so dependency installation is cached; add a .dockerignore
Container must run as root for a legacy reasonIsolate it, drop all capabilities, and treat it as a tracked exception
Debugging a production imageBuild a separate debug variant; do not ship shells and toolchains in the production image
Regulated environmentPin base images by digest, scan in CI, and sign images before deployment

Implementation Checklist

  • [ ] Base image is an official, minimal variant pinned to a specific version
  • [ ] Build uses multiple stages; no compilers or dev dependencies in the final image
  • [ ] Dependency manifests are copied before source code so the layer cache is effective
  • [ ] A .dockerignore excludes .git, local dependencies, and secret files from the context
  • [ ] Final image runs as a named non-root user with file ownership set via --chown
  • [ ] No secrets are passed as build arguments or baked into layers; they are injected at runtime
  • [ ] A HEALTHCHECK exercises a real readiness endpoint
  • [ ] CPU and memory limits and log rotation are set wherever the container runs
  • [ ] Images are scanned in CI and the pipeline fails on fixable critical vulnerabilities
  • Trade-offs

    Minimal images are harder to debug because they omit shells and common utilities; expect to attach ephemeral debug containers or rely on logs and metrics instead. Aggressive layer caching speeds builds but can hide staleness, so base images still need scheduled rebuilds to pick up patches. Pinning versions improves reproducibility at the cost of a deliberate update process; without automation such as dependency bots, pinned images quietly age. Multi-stage builds add Dockerfile complexity, and for a trivial static site the extra stages may not repay the effort.

    When Not to Use

  • You need a different kernel or operating system than the host: containers share the host kernel. Use a virtual machine when the workload requires another OS, kernel modules, or kernel-level tuning.
  • The workload is a stateful system you do not yet operate confidently: databases and message brokers run well in containers, but if your team has no backup and recovery practice for them, a managed service is the safer choice.
  • Strong multi-tenant isolation is a hard requirement: containers share a kernel, so hostile tenants belong in separate VMs or dedicated hosts, not just separate containers.
  • Conclusion

    Good Docker images are boring: small, pinned, scanned, and built the same way every time. Multi-stage builds, disciplined layer ordering, a non-root user, and explicit runtime limits cover most of what separates a development Dockerfile from a production one. Apply the checklist incrementally, starting with pinning and scanning, and the rest becomes routine maintenance rather than a rewrite.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.