Course contentsShow
← Cloud and Infrastructure
Lesson 1030 of 2,98920. Docker in DepthFree lesson

Dependency Installation Best Practices

Copying dependency manifests first and installing before copying application code.

Dependency Installation Best Practices

What you'll learn: How to structure your Dockerfile to install dependencies efficiently by separating dependency manifests from application code.

The Problem: Rebuilding Dependencies Unnecessarily

When you change even one line of your application code and rebuild a Docker image, you don't want to reinstall all your dependencies—that wastes time and bandwidth. The solution lies in understanding how layer caching works with your dependency files.

Copy Dependencies First, Code Later

The key principle: copy your dependency manifest files (like package.json, requirements.txt, go.mod) before copying your application code.

Here's why this matters:

# ❌ Poor practice - invalidates cache on any code change
COPY . /app
RUN npm install

# ✅ Best practice - cache dependencies separately
COPY package.json package-lock.json /app/
RUN npm install
COPY . /app

In the optimized version, when you modify your application code but dependencies remain unchanged, Docker reuses the cached layer from RUN npm install. Only the final COPY layer rebuilds—saving minutes or even hours in large projects.

The Analogy

Think of it like restocking a kitchen: if your recipe (code) changes but the ingredient list (dependencies) stays the same, you don't need to go shopping again. You only re-shop when the ingredient list itself changes.

Order Matters

Place dependency installation as early as possible in your Dockerfile, right after selecting your base image. This maximizes cache reuse across builds since dependencies typically change far less frequently than application code.

Key Takeaway: Always copy dependency manifests first, install dependencies, then copy application code—this pattern dramatically improves build speed by leveraging layer caching effectively.