Skip
Arish's avatar

34. Image Optimization


Choose Small Base Images

dockerfile
1# Size comparison
2ruby:3.2          # ~900MB
3ruby:3.2-slim     # ~200MB
4ruby:3.2-alpine   # ~80MB

Remove Unnecessary Files

dockerfile
1RUN bundle install && \
2    rm -rf ~/.bundle/cache && \
3    rm -rf /usr/local/bundle/cache/*.gem

Use Multi-Stage Builds

dockerfile
1FROM node:18 AS assets
2WORKDIR /app
3COPY package*.json ./
4RUN npm ci
5COPY . .
6RUN npm run build
7
8FROM ruby:3.2-slim AS production
9COPY --from=assets /app/public/assets public/assets
10# Only production dependencies

Optimize for Cache

dockerfile
1# Copy dependency files first
2COPY Gemfile Gemfile.lock ./
3RUN bundle install
4
5COPY package*.json ./
6RUN npm ci
7
8# Then copy source
9COPY . .

Analyze Image Size

bash
1# View layers
2docker history myapp:latest
3
4# Detailed analysis with dive
5dive myapp:latest

BuildKit Features

bash
1# Enable BuildKit
2DOCKER_BUILDKIT=1 docker build .
3
4# Cache mounts
5RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt