DevopsIntermediate

Containers and Docker: Essential Resources and Best Practices

Admin KC
5 min read

TL;DR

A curated reference guide to containers and Docker: official documentation, Dockerfile best practices, security, Compose, networking, and multi-stage builds.

Containers and Docker: Essential Resources and Best Practices

Executive Summary

Most Docker pain is self-inflicted in the Dockerfile: 1.2 GB images built from a full OS, containers running as root, latest tags that change under you, and secrets baked into layers where anyone with the image can read them. None of this needs exotic tooling to fix. Multi-stage builds, small bases, a non-root user, pinned versions, and a .dockerignore file cover most of it. This guide walks through the practices that make images small, builds reproducible, and containers safe to run.

Why This Matters

An image is your deployment unit and your supply chain in one artifact. A bloated image slows every pull, every autoscale event, and every cold start. An unpinned base is a build that can break — or silently change — without any commit from you. And a container running as root turns a single application bug into a host-level incident. These are cheap problems to prevent and expensive ones to debug after the fact.

Core Concepts

Multi-Stage Builds: Ship the Artifact, Not the Toolchain

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

# Runtime stage
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]

Compilers, dev dependencies, and source code stay in the build stage. The runtime image carries only what the process needs — often 5–10x smaller.

Layer Hygiene

  • One logical change per layer, ordered least-changing first: dependencies before source, so the cache works for you.
  • Combine related RUN commands and clean package caches in the same layer that created them — deleting files in a later layer does not shrink the image.
  • Always ship a .dockerignore (.git, node_modules, .env, test fixtures). Build context is uploaded on every build; a fat context is a slow build and a leak risk.
  • Pin Everything

    FROM node:20-alpine is a floor, not a ceiling. For production, pin to a digest (node:20-alpine@sha256:…) and let a bot (Renovate, Dependabot) propose bumps as pull requests. "Reproducible" means the same Dockerfile produces the same image next month.

    Run as Non-Root, Drop Capabilities

    USER node

    Most application processes need no root. Pair a non-root user with --cap-drop=ALL (adding back only what is genuinely required) and a read-only root filesystem where the app allows it. These three flags close off the most common container-escape paths.

    Compose for Local Development

    Docker Compose is the right scope for local stacks and small single-host deployments: services, named volumes, healthchecks, and depends_on: condition: service_healthy give you a reproducible dev environment in one file. Treat Compose files as development tooling — production orchestration belongs to Kubernetes or a managed container service.

    Networking in One Paragraph

    User-defined bridge networks give you DNS by service name and isolation between stacks; the default bridge does neither well. Publish only the ports the outside world needs (-p), and keep databases and admin surfaces on internal networks. If two containers must not talk to each other, they belong on different networks — containers on the same network can always reach each other.

    Decision Framework

    SituationReach for
    Local multi-service developmentDocker Compose
    Single small production serviceCompose on a VM, or a managed container service (ECS Fargate, Cloud Run, Container Apps)
    Many services, scaling, self-healingKubernetes
    Image too bigMulti-stage build + slim/alpine base + .dockerignore audit
    Build secrets needed at build timeBuildKit --mount=type=secret — never ARG/ENV for secrets

    Implementation Checklist

  • [ ] Multi-stage build; runtime image contains no toolchain or source
  • [ ] Base images pinned by version (digest for production)
  • [ ] USER is non-root in the final stage
  • [ ] .dockerignore committed and reviewed
  • [ ] No secrets in ENV, ARG, or any layer — verify with an image history scan
  • [ ] Image scanned in CI (Trivy, Docker Scout, or equivalent) with a failing threshold
  • [ ] Healthcheck defined so orchestrators can detect a wedged process
  • [ ] Logs go to stdout/stderr; the container writes no local state that matters
  • Trade-offs

    Alpine-based images are tiny but use musl libc — native modules occasionally misbehave, and debugging tools are absent by design. Distroless images go further (no shell at all), which is excellent for security and painful the first time you need to inspect a running container. Slim Debian bases are the pragmatic middle for most teams. Choose per workload, and standardise the exception process rather than the exception.

    When Not to Use Docker

  • Stateful systems with exotic storage needs can be simpler on VMs until you have the operational maturity for StatefulSets and operators.
  • Windows-only legacy workloads may cost more to containerise than to rehost as-is.
  • A single static site does not need a container; object storage plus a CDN is simpler and cheaper.
  • References

    Here are essential resources for learning about containers and Docker:

  • Docker Documentation - Official Docker documentation
  • Docker Best Practices - Official best practices guide
  • Container Security - Docker security guide
  • Docker Compose - Multi-container applications
  • Docker Hub - Container image repository
  • Container Runtime Interface - Kubernetes container runtimes
  • OCI Specifications - Open Container Initiative standards
  • BuildKit Documentation - Advanced image building
  • Docker Networking - Container networking guide
  • Alternative Runtimes - Other container runtimes
  • Multi-stage Builds - Optimizing Docker builds
  • Container Orchestration - Introduction to orchestration
  • These resources provide comprehensive information about containers and Docker technology.

    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.