Instruction Best Practices
You'll learn how to write efficient Dockerfiles by mastering instruction order, layer caching, and proven patterns.
Why Instruction Order Matters
Every Dockerfile instruction creates a new layer. Docker caches these layers and reuses them when nothing changes. Think of it like building with LEGO blocks—if the bottom blocks stay the same, you don't need to rebuild them.
The golden rule: put instructions that change rarely at the top, and instructions that change frequently at the bottom.
Optimize for Cache Hits
Place FROM, ENV, and ARG instructions first—these rarely change. Install system dependencies next with RUN commands. Copy dependency files (like package.json or requirements.txt) and install them before copying your application code. This way, Docker can reuse the dependency layer even when your code changes.
FROM node:18
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
CMD ["node", "app.js"]
Common Patterns
Combine multiple RUN commands with && to reduce layers. Clean up in the same instruction where you create mess (like removing package caches). Use .dockerignore to prevent copying unnecessary files. Set USER near the end, after installing packages that need root. Place HEALTHCHECK and LABEL instructions where they don't break cache chains.
Avoid installing unnecessary packages. Each layer adds size and attack surface.
Key Takeaway: Structure your Dockerfile with stable instructions first and volatile ones last; this maximizes layer cache reuse, dramatically speeds up builds, and creates smaller, more efficient images.