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
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article
PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More image

PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More

Read article
Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released image

Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released

Read article
Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite image

Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite

Read article