Back to all terms
ServerNode 1Node 2Infrastructure
Infraintermediate

Dockerfile Best Practices

Write efficient, secure, and maintainable Dockerfiles that produce minimal, production-ready images.

Also known as: Dockerfile optimization, Docker image optimization, Dockerfile patterns

Description

Dockerfile best practices encompass a set of patterns and conventions for writing Dockerfiles that produce small, secure, and cache-efficient container images. Key principles include ordering instructions from least to most frequently changed (to maximize layer caching), combining RUN statements to reduce layer count, and using .dockerignore to exclude unnecessary files from the build context.

Security-oriented practices include running containers as a non-root user, pinning base image versions to specific SHA digests rather than mutable tags, avoiding the installation of unnecessary packages, and removing package manager caches after installation. Using COPY instead of ADD (unless tar extraction is needed), setting appropriate file permissions, and avoiding storing secrets in image layers are all critical for production Dockerfiles.

Performance practices include leveraging BuildKit for parallel stage execution and cache mounts, using multi-stage builds to separate build dependencies from runtime artifacts, and choosing minimal base images like Alpine or distroless. Proper use of HEALTHCHECK instructions, ENTRYPOINT vs CMD semantics, and signal handling (ensuring PID 1 handles SIGTERM correctly with tini or dumb-init) are essential for production container lifecycle management.

Prompt Snippet

Create a multi-stage Dockerfile with a builder stage using node:20-alpine for dependency installation and TypeScript compilation, and a production stage using gcr.io/distroless/nodejs20-debian12. Copy only the built artifacts and production node_modules. Pin the base image to a specific SHA256 digest, set NODE_ENV=production, run as non-root user (uid 1001), configure a HEALTHCHECK using curl against /healthz every 30s with 3s timeout and 3 retries, and use tini as PID 1 init process for proper signal forwarding.

Tags

dockerdockerfileoptimizationsecuritybest-practices