Speed Up Docker Builds with Layer Caching
Reordering your Dockerfile can cut build times from minutes to seconds.
What
Docker caches each layer of your image. When a layer changes, every layer after it is rebuilt from scratch. By placing instructions that change less frequently (like installing dependencies) before instructions that change often (like copying source code), you maximize cache hits.
Why It Matters
Without proper layer ordering, even a one-line code change forces Docker to reinstall all your dependencies. This wastes time in development and especially in CI/CD pipelines where every second counts.
Example
# Bad: copies everything first, then installs
COPY . /app
RUN npm ci
# Good: install deps first, then copy source
COPY package*.json /app/
RUN npm ci
COPY . /appCommon Mistake
Putting COPY . /app before RUN npm ci. This means any source code change invalidates the npm ci cache, forcing a full reinstall every build.
Quick Fix
Always copy dependency files (package.json, requirements.txt, go.mod) and install dependencies BEFORE copying the rest of your source code.
Key Takeaways
- 1Docker caches each layer
- 2Changed layer = rebuild everything after it
- 3COPY package.json FIRST, then npm ci
- 4COPY source code LAST
- 5Result: dramatically faster rebuilds
Was this tip helpful?
Help us improve the DevOpsPath daily collection