Skip
Arish's avatar

33. Dockerfile Best Practices


Layer Caching

Order commands from least to most frequently changed:

dockerfile
1# Good - dependencies cached
2FROM ruby:3.2
3WORKDIR /app
4COPY Gemfile Gemfile.lock ./
5RUN bundle install
6COPY . .
7
8# Bad - cache busted every time
9FROM ruby:3.2
10WORKDIR /app
11COPY . .
12RUN bundle install

Minimize Layers

dockerfile
1# Bad - multiple layers
2RUN apt-get update
3RUN apt-get install -y git
4RUN apt-get install -y curl
5RUN rm -rf /var/lib/apt/lists/*
6
7# Good - single layer
8RUN apt-get update && \
9    apt-get install -y git curl && \
10    rm -rf /var/lib/apt/lists/*

Use Specific Tags

dockerfile
1# Bad
2FROM ruby:latest
3
4# Good
5FROM ruby:3.2.2-slim-bullseye

Clean Up

dockerfile
1RUN apt-get update && \
2    apt-get install -y build-essential && \
3    bundle install && \
4    apt-get purge -y build-essential && \
5    apt-get autoremove -y && \
6    rm -rf /var/lib/apt/lists/*

Use .dockerignore

Exclude unnecessary files to reduce build context.

Multi-Stage Builds

Separate build and runtime for smaller images.