Build Cache & .dockerignore

Order for Fast Rebuilds

Docker reuses a cached layer until one instruction (or a file it copies) changes; every layer after it is rebuilt. Put rarely-changing steps first:

# good: dependencies are only reinstalled when requirements.txt changes
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

# bad: any code change re-runs pip install
COPY . .
RUN pip install -r requirements.txt

.dockerignore

Example

Files listed in .dockerignore are not sent to the builder, which keeps builds fast and keeps secrets out of images:

.dockerignore

.git
node_modules
__pycache__/
*.pyc
.venv/
.env
*.log
Dockerfile
docker-compose.yml

Note: Never COPY a .env file or credentials into an image: anyone who can pull the image can read them.