4,000 emails/month for free | Mailtrap sends real emails now!

Creating Multi-Stage Docker Builds for Laravel

Published on by

Creating Multi-Stage Docker Builds for Laravel image

Starting in Docker version 17.05 multi-stage builds are available to help you optimize Dockerfiles. Using multi-stage builds is a clean way to set up a Docker build pipeline that simplifies the requirements you need on your CI/build server to create a Docker image for your app.

If you’re not familiar with multi-stage builds, no worries! Let me summarize by saying that before multi-stage builds if you wanted to install composer dependencies and frontend dependencies during a docker build of your app, your Docker image would need to have the necessary dependencies such as Node.js installed and Composer PHP.

The resulting Dockerfile and image can be fairly messy and frustrating to maintain.

Another approach that I’ve taken in my build environment is installing composer and node dependencies on the server running the build, and then copying the artifacts such as the vendor/ folder and production-ready JS and CSS build files.

A simplified version of building dependencies outside of Docker and copying them it might look something like the following:

#!/usr/bin/env bash
 
set -e
 
tag=${1:-latest}
 
composer install \
--ignore-platform-reqs \
--no-interaction \
--no-plugins \
--no-scripts \
--prefer-dist
 
yarn install && yarn production
 
docker build -t my-app:$tag .

The above script is a simplified version to illustrate how you’d prepare the PHP and frontend dependencies and the docker build would copy the project into the image.

By using multi-stage builds, you no longer need to install those dependencies or cram them all into your Dockerfile, thus bloating your final image size!

Multi-Stage Approach

Using a Laravel 5.6 application as an example, we can start building the dependencies for production-ready images in one Dockerfile that contains multiple stages.

Setup

If you’re following along, create a demo project from the command line with the following:

laravel new multi-stage-demo
 
cd multi-stage-demo
 
# Create the Dockerfile file
touch Dockerfile
 
# Generate the yarn lockfile
yarn install
 
git init
git add .
git commit -m"First commit"

Next, create a .dockerignore file in the root of your Laravel app with the following:

.git/
vendor/
node_modules/
public/js/
public/css/
yarn-error.log

We aren’t going to go too deeply into how the .dockerignore file works, but the important part to understand is that it prevents copying the defined paths during a docker build. The ignore file means that the vendor/ folder won’t get copied in during a COPY or ADD instruction in the Dockerfile:

# copies the Laravel app, but skips the ignored files and paths
COPY . /var/www/html

For example, ignoring the vendor/ folder means that we get a pristine build of the composer dependencies from our build.

The Dockerfile

Our application Dockerfile will break up each stage of the application build with three parts:

  1. Install Composer Dependencies
  2. Build frontend dependencies
  3. Copy our app code and artifacts from the first two stages

Stage 1

The first stage will be composer dependencies. We can use the official composer image to install our application dependencies first in the Dockerfile within the root of the project:

#
# PHP Dependencies
#
FROM composer:1.7 as vendor
 
COPY database/ database/
 
COPY composer.json composer.json
COPY composer.lock composer.lock
 
RUN composer install \
--ignore-platform-reqs \
--no-interaction \
--no-plugins \
--no-scripts \
--prefer-dist

Note the as vendor portion of the FROM instruction. We will reference this name later when we copy the artifact (the vendor/ folder) later in the Dockerfile.

The first stage of our Dockerfile copies a few necessary paths that Laravel configures in the composer.json autoload classmap. Next, it copies in the composer JSON and lock files. Finally, it runs a composer install to install the dependencies.

If you rerun a build you can peek around the image and see the results of the composer install command:

docker build -t ms-laravel-test -f docker/Dockerfile .
 
docker run --rm -it ms-laravel-test bash
 
# Inside the running container
bash-4.4# ls -la vendor/
...
bash-4.4# exit

We are done with stage one! This stage of the build installed all the necessary vendor/ files that we’ll copy later.

Stage 2

The next stage of the build is installing our application frontend dependencies using Yarn (or NPM if that’s your thing). After the first stage, append the following to the Dockerfile:

#
# Frontend
#
FROM node:8.11 as frontend
 
RUN mkdir -p /app/public
 
COPY package.json webpack.mix.js yarn.lock /app/
COPY resources/assets/ /app/resources/assets/
 
WORKDIR /app
 
RUN yarn install && yarn production

Once again we are using an official image, this time the LTS version of Node, which comes with yarn as well. We create a /app/public directory and copy in the needed files into the /app path so that Laravel Mix knows can build the JavaScript and CSS.

Last, we install the package dependencies and run the yarn production command to finish installing our frontend assets!

At this point we can build our image again and inspect the frontend dependencies:

docker build -t ms-laravel-test .
docker run --rm -it ms-laravel-test bash
 
# Inside the running container
root@faa6904a98df:/app# ls -la
root@faa6904a98df:/app# ls -la public/{js,css}
root@faa6904a98df:/app# exit

Feel free to investigate the frontend paths while in the container and finally exit the running container. We’re ready to build the final stage using the artifacts we’ve created!

Stage 3

The final stage of our Docker build involves copying in the application files from the source code and copying the artifacts from earlier build stages.

To create the final build stage, append the following to the Dockerfile:

#
# Application
#
FROM php:7.2-apache-stretch
 
COPY . /var/www/html
COPY --from=vendor /app/vendor/ /var/www/html/vendor/
COPY --from=frontend /app/public/js/ /var/www/html/public/js/
COPY --from=frontend /app/public/css/ /var/www/html/public/css/
COPY --from=frontend /app/mix-manifest.json /var/www/html/mix-manifest.json

We first copy the application into the image. The .dockerignore file ensures that ignored paths are not copied from the host machine into the image.

Note the COPY --from instructions which reference the names of earlier stages (i.e. FROM node:8.11 as frontend). We are copying the artifacts from earlier stages into their proper place within the final image.

If you build the image one last time, you can see the full-constructed application without the overhead of node packages or composer scripts!

docker build -t ms-laravel-test .
docker run --rm -it ms-laravel-test bash
 
# Inside the running container
root@1d6251d2362c:/var/www/html# ls -la
...

Our final image is a PHP 7.2 image with Apache, however, to run this app we would need to modify the default Vhost config file to point to the /var/www/html/public that Laravel expects. We’ll skip that since this article’s focus is using multi-stage builds ;)

Here’s the final Dockerfile in full:

#
# PHP Dependencies
#
FROM composer:1.7 as vendor
 
COPY database/ database/
 
COPY composer.json composer.json
COPY composer.lock composer.lock
 
RUN composer install \
--ignore-platform-reqs \
--no-interaction \
--no-plugins \
--no-scripts \
--prefer-dist
 
#
# Frontend
#
FROM node:8.11 as frontend
 
RUN mkdir -p /app/public
 
COPY package.json webpack.mix.js yarn.lock /app/
COPY resources/assets/ /app/resources/assets/
 
WORKDIR /app
 
RUN yarn install && yarn production
 
#
# Application
#
FROM php:7.2-apache-stretch
 
COPY . /var/www/html
COPY --from=vendor /app/vendor/ /var/www/html/vendor/
COPY --from=frontend /app/public/js/ /var/www/html/public/js/
COPY --from=frontend /app/public/css/ /var/www/html/public/css/
COPY --from=frontend /app/mix-manifest.json /var/www/html/mix-manifest.json

Learn More

The first place you should check out to learn more about multi-stage builds is Use multi-stage builds from the official Docker documentation. Multi-stage builds are useful and an excellent way to build your final application artifact without many local dependencies.

If you want to learn more about developing with Docker and PHP, including Laravel, check out my book Docker for PHP Developers. If you don’t want the starter Laravel code, you can also get the book only version. Laravel News readers get a discount on both versions of the book! You can learn more about the book announcement here.


The links included are affiliate links which means if you decide to buy Laravel News gets a little kickback to help run this site.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article