What is a multi stage Docker build, and how does it help produce a smaller, more secure production image for a PHP application?
Short answer
A multi stage build lets you use multiple FROM statements within a single Dockerfile, where an early stage might include development tools and dependencies needed only for building the application, such as Composer and development dependencies, while a later, final stage copies…
Advertisement
AModel answer
A multi stage build lets you use multiple FROM statements within a single Dockerfile, where an early stage might include development tools and dependencies needed only for building the application, such as Composer and development dependencies, while a later, final stage copies over only the actually necessary compiled application files, resulting in a significantly smaller final production image that does not carry along unnecessary build time tools and reduces the potential attack surface.
FROM composer:2 AS build
COPY . /app
RUN composer install --no-dev --optimize-autoloader
FROM php:8.2-fpm
COPY --from=build /app /var/www/htmlReal-world example
A team reduces their production Docker image size significantly by using a multi stage build that installs Composer dependencies in a temporary build stage, then copies only the final application files into a clean, minimal production image.
Likely follow-ups
- What security benefits come from having a smaller final production image?
- Can a multi stage build have more than two stages?
Related topics