Docker Build Cache Invalidation Strategies for Laravel Apps

Recently I refactored our Laravel monolith to run inside a minimal PHP‑FPM image built on Alpine. The biggest pain point was the rebuild time when we added a new Composer package or updated env files. Docker’s layer cache is great, but the cache‑invalidation strategy we pick dramatically affects both CI latency and developer iteration speed.

Typical Dockerfile

FROM php:8.2-fpm-alpine AS base
WORKDIR /var/www

# 1. Install system deps
RUN apk add --no-cache \
    libzip-dev \
    oniguruma-dev && \
    docker-php-ext-install zip pdo_mysql

# 2. Copy composer files and install deps
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader

# 3. Copy application code
COPY . .
RUN php artisan config:cache && php artisan route:cache

If we keep the COPY . . after the Composer install, any code change forces a full reinstall, which is costly. Moving the COPY . . earlier, or adding a .dockerignore that excludes vendor/, node_modules/, and storage/ can keep the Composer layer cached, but it also means we have to run composer install on every CI run when only a PHP file changed.

Trade‑offs

  • Layer ordering – Put immutable steps first (system packages), then Composer lock, then source. Fast when only code changes, slow when dependencies change.
  • Multi‑stage builds – Build assets in a node stage, copy only the compiled public/ folder. Reduces final image size but adds another stage to maintain.
  • Cache busting args – ARG CACHE_DATE=$(date +%s) before Composer install forces a fresh install when we explicitly need it (e.g., nightly security updates) without breaking normal dev cycles.

Open questions

  1. In your CI pipelines, do you prefer a single Dockerfile with conditional --build-arg to force cache bust, or separate Dockerfiles for “dev” and “prod” builds?
  2. How do you handle environment‑specific config (e.g., .env.testing) without invalidating the Composer layer? Do you mount config at runtime or bake it into the image?

Looking forward to hearing what works in production.

DevOps#Laravel#DevOps#Docker
0

0 Answers

Post Your Answer

Use ``` code ``` for syntax highlighting