Multi-Stage Builds and Optimization
Shrink images and separate build from runtime.
Why Multi-Stage
A single-stage image carries Composer, build deps, dev headers, and your tests/ folder into production. Multi-stage builds let you compile/install in a fat builder stage and copy only the finished artifacts into a slim runtime stage.
Result: smaller images, smaller attack surface, faster pulls, and no compilers shipped to prod.
Named Stages
Each FROM ... AS name starts a new stage. Later stages can COPY --from=name files out of earlier ones. Only the final stage becomes your image; intermediate stages are discarded (but cached).
# Stage 1: dependencies
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --prefer-dist --ignore-platform-reqs
# Stage 2: runtime
FROM php:8.3-fpm-alpine AS runtime
WORKDIR /app
COPY --from=vendor /app/vendor ./vendor
COPY . .All lessons in this course
- Containerizing a PHP Application
- Multi-Stage Builds and Optimization
- Docker Compose for Local Stacks
- CI/CD with GitHub Actions