This reference guide codifies the fundamental “golden rules” and production best practices for containerization with Docker and container orchestration with Kubernetes. Grounded in established cloud-native patterns and technical handbooks, these rules emphasize immutability, security, declarative management, high availability, and optimal resource utilization.
Part I: Docker Golden Rules
1. Maintain Single-Process & Decoupled Architecture
- Rule: Design containers to run a single process or single functional service per container.
- Rationale: Decoupling microservices allows individual components to scale independently and fail without cascading. Inter-container communication should be handled via defined networks or container linking rather than bundling multiple daemons into one image.
- Key Practices: Avoid running init systems (like
systemdorsupervisord) inside containers unless absolutely necessary for host-emulation testing.
2. Treat Containers as Ephemeral & Immutable
- Rule: Containers must be treated as short-lived, disposable entities.
- Rationale: Runtime modifications inside a running container are lost upon restart and break deployment reproducibility.
- Key Practices:
- Never manually edit files inside a running container.
- Store all persistent application state and dynamic data outside the container lifecycle using Docker Volumes or volume mounts.
- Manage runtime configuration changes via environment variables (
ENV).
3. Master Dockerfile Layer Optimization & Cache Management
- Rule: Order Dockerfile directives strategically and combine related build steps.
- Rationale: Docker images use union filesystems where every directive adds a read-only layer. Reordering directives maximizes caching efficiency, while combining commands reduces image overhead.
- Key Practices:
- Order by Change Frequency: Place instructions that change rarely (base image, system packages, app dependencies) near the top, and frequently changing code near the bottom.
- Chain Commands: Combine system update and package installation commands into a single
RUNline with cleanup (e.g., `RUN apt-get update && apt-get install -y