Docker Compose — Build Cache & Secrets

1 minute read

Speed up builds with caching strategies and pass sensitive data securely during builds.

Build Cache

Docker caches each layer. If a layer hasn’t changed, it’s reused:

Step 1: FROM node:20-alpine          → Cached ✓
Step 2: COPY package*.json ./        → Cached ✓ (files unchanged)
Step 3: RUN npm ci                   → Cached ✓ (package.json unchanged)
Step 4: COPY . .                     → Rebuilds (source changed)
Step 5: RUN npm run build            → Rebuilds

Cache Optimization in Dockerfile

# ✗ BAD: Cache busted on every source change
COPY . .
RUN npm ci && npm run build

# ✓ GOOD: Dependencies cached separately
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

External Cache (BuildKit)

services:
  api:
    build:
      context: ./api
      cache_from:
        - type=registry,ref=myregistry/api:cache
      cache_to:
        - type=registry,ref=myregistry/api:cache,mode=max

This stores/retrieves cache layers from a registry — great for CI/CD.

No Cache Build

docker compose build --no-cache

Build Secrets

Pass sensitive data during build without embedding in the image:

compose.yml:

services:
  api:
    build:
      context: ./api
      secrets:
        - npm_token

secrets:
  npm_token:
    file: ./secrets/npm_token.txt

Dockerfile:

FROM node:20-alpine
WORKDIR /app

# Mount secret during RUN (not stored in image layer)
RUN --mount=type=secret,id=npm_token     NPM_TOKEN=$(cat /run/secrets/npm_token)     npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN &&     npm ci

COPY . .
CMD ["node", "server.js"]

Build Secrets vs Build Args

Feature Build Args Build Secrets
Visible in image history Yes No
Available in RUN Via $ARG_NAME Via --mount=type=secret
Security Not secure Secure
Use case Version numbers Tokens, passwords

SSH Agent Forwarding

For private git repos during build:

services:
  api:
    build:
      context: .
      ssh:
        - default
RUN --mount=type=ssh git clone git@github.com:org/private-repo.git

Summary

Feature Purpose
Layer caching Reuse unchanged layers
cache_from/to External cache registry
–no-cache Force full rebuild
Build secrets Secure build-time data
SSH forwarding Private repo access

Quick Reference

Item Detail
Layer caching Dependencies before source code
cache_from Pull cache from registry
–no-cache Skip all caching
Build secrets –mount=type=secret in RUN
vs args Secrets not stored in image history
SSH –mount=type=ssh for private repos