Deploy a Dockerized Laravel application
Fullstack Developer and Tech Author
As web applications become more complex, software engineering teams must rely on many different products and services to create the best developer experience. The application development ecosystem has grown beyond version control and hosting deployment. Managing the deployment of new features across all services can create a serious bottleneck in the software development lifecycle. It also introduces the risk of human error.
In this tutorial, I will describe how to deploy a Dockerized Laravel application to Microsoft Azure using GitHub for version control. You will take a previously-built Laravel API project, build a container image out of it, and then push the image to the Azure container registry. Then, you will learn how to create an Azure web service as an application and connect the container image to it.
Microsoft Azure Web Apps is a platform as a service (PaaS) that lets you publish web apps running on multiple frameworks, written in different programming languages. You can then use a CI/CD tool (like CircleCI) to build, test, and deploy web applications for a faster release cycle, more efficient development, and higher-quality code.
Prerequisites
In addition to a basic understanding of Laravel and PHP, you will need the following items to get the most from this tutorial:
- PHP 8.3 or later and Composer installed on your local machine
- Docker Desktop installed on your local machine — follow Docker’s tutorial for Windows or macOS
- A GitHub account
- A CircleCI account
- An Azure account
Our tutorials are platform-agnostic, but use CircleCI as an example. If you don’t have a CircleCI account, sign up for a free one here.
Cloning the demo project
Clone the sample Laravel project by running this command:
git clone https://github.com/CIRCLECI-GWP/docker-laravel-api.git
Setting up the demo project
Next, go to the root of the new folder you just created. Set up the project by running these commands:
cd docker-laravel-api
composer install
cp .env.example .env
php artisan key:generate
php artisan serve
These commands will change directory into the docker-laravel-api project from the terminal and:
- Install all the project’s dependencies
- Create a
.envfile and copy the content of.env.examplefile into it - Generate an application key
- Run the application
By default, your application will be served to http://127.0.0.1:8000/. Go to this endpoint to view the .json response.
You can use this command to run the unit tests:
php vendor/bin/phpunit
Reviewing the deployment strategy
Now that you have the application running locally, it is a good time to review your deployment strategy. There is no need for any project code changes other than including the configuration file to set up deployment for CircleCI.
In order, you will need to:
- Create a registry to host your container image on Azure container registry (ACR) and create an access token for it. ACR is a private registry owned by Microsoft for hosting Docker images.
- Create a container image for the project, build, and then run the container locally.
- Publish the Docker image to the Azure container registry.
- Create an Azure web app and link it with the published container image.
- Enable continuous deployment and create a configuration file to build and deploy the container image on CircleCI.
- Push the project to GitHub and connect with CircleCI.
- Deploy the container image to the Azure container registry.
Creating an Azure container registry
If you do not have one already, create an account on Azure. In the Azure portal, search for Container registries and open it. Click Create to create a new registry.
On the Basics tab, select your subscription and resource group, then enter a registry name, a location, and a pricing plan. The default plan is Standard, but Basic is enough for this tutorial. Registry names can only contain letters and numbers, so no dashes.
Note: You can create a new resource group for this project or use an existing one.
The Domain name label scope setting decides your registry’s login server. With Unsecure, the default, the login server is <registry-name>.azurecr.io. The other options add a unique hash, such as <registry-name>-<hash>.azurecr.io. Either works for this tutorial, because you’ll use your registry’s actual login server everywhere.
Click Review + create. You will be redirected to a page where you can review the registry information. Click Create to set up a new registry instance.
When the deployment completes, open the registry and copy the Login server value from the Overview page. You’ll need it in the next steps.
Creating an access token for the registry
In this section, you’ll create a token that can push images to the registry. This step is crucial to the deployment process. The token lets you log into the Azure container registry from the CLI, and later from CircleCI, and push images to it. Unlike the registry’s admin user, which Microsoft recommends only for testing, a token only has access to the repositories you choose.
Open the registry and go to Repository permissions > Tokens. Click Add.
Enter a token name, such as circleci-push. Under Scope map, click Create new scope map. Name the scope map, enter laravelapidocker as the repository, and select the content/read and content/write permissions. Click Create to save the scope map, then click Create again to create the token. The repository doesn’t need to exist yet; your first push creates it.
A new token has no password. Open the token and click Generate in the password1 row. In the pane that opens, click Generate, then click Yes to confirm. Copy the password right away; you can’t view it again after you close the pane. Keep the token name and password somewhere handy; you’ll need them later in the tutorial.
Containerizing the application locally
Your next step is writing a custom Docker file that will allow you to build a container image. The demo project already includes one. If you’re working on your own project, create a new file named Dockerfile at the root of the application. Open the file and paste this content into it:
FROM php:8.5
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
RUN apt-get update && apt-get install -y zlib1g-dev \
libzip-dev \
unzip
RUN docker-php-ext-install pdo pdo_mysql sockets zip
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN composer install
CMD php artisan serve --host=0.0.0.0 --port=8000
EXPOSE 8000
PHP 8.5 is used as the base image. The subsequent commands copy Composer from the official Composer image, install the extensions for a Laravel application, and enable the PHP PDO and MySQL extensions.
When the installation is complete, set the working directory to app and copy the files from your local machine into the working directory of the container. Then run composer install and include the command to run the application.
The project also has a .dockerignore file that keeps your local .env file, vendor, and node_modules folders out of the image. That way, the image you build locally matches the one CircleCI builds later.
Building the Docker image
First, save your registry’s login server in a REGISTRY variable. Replace the value with the Login server you copied earlier:
export REGISTRY=laravelapidocker.azurecr.io
To build a Docker image for the project, run:
docker build -t $REGISTRY/laravelapidocker:latest .
If you’re using a Mac with Apple silicon, run this command instead, so the image matches the linux/amd64 platform that Azure runs:
docker build --platform linux/amd64 -t $REGISTRY/laravelapidocker:latest .
This command will look in the project for the Dockerfile and build the container image based on the contained instructions. Notice that the image name starts with the login server of the registry created earlier. The benefit of this approach is to easily map the container image with the Azure container registry.
Running the Docker image
Now that you have successfully built the local version of the container image, make sure it works. Run:
docker run -d -p 8000:8000 $REGISTRY/laravelapidocker
This will run the app on port 8000. Check it by visiting http://localhost:8000.
Pushing the Docker image to Azure Registry
Next, log into the Azure container registry created earlier and push the container image to it. From the terminal, run:
export DOCKER_USER=circleci-push
export DOCKER_PASS=<your-token-password>
echo $DOCKER_PASS | docker login $REGISTRY -u $DOCKER_USER --password-stdin
Replace the values with your own:
DOCKER_USER: The name of the token you created for the container registry.DOCKER_PASS: The token password you generated.
After you log in, push the image to the Azure registry by running:
docker push $REGISTRY/laravelapidocker:latest
Creating an Azure web app for the container
Next, you need to create an Azure Web App and connect it with the container image. In the Azure portal, search for App Services and open it. Click Create, then Web App.
You will be redirected to the Create Web App page. Select an Azure subscription and a resource group. Create a new resource group if you need to. Enter a name for the app, then set Publish to Container and Operating System to Linux. Choose the same region as your registry. The default pricing plan is a paid Premium tier; click Explore pricing plans, choose Free F1, and click Select if you only want to try the tutorial.
From the Container tab, keep Sidecar support turned on, set Image Source to Azure Container Registry, and select your registry. Keep Authentication set to Managed identity, and under Identity, select the new identity the portal offers. With a managed identity, the web app pulls the image without a registry password. Enter laravelapidocker as the Image and latest as the Tag; the portal doesn’t fill them in when you use a managed identity. Then change Port to 8000, the port the container listens on.
When you click Review + create, you will be redirected to a page where you can review the web app details. Click Create to set up a new Azure web app.
When the deployment completes, click Go to resource and open the Default domain URL from the web app’s Overview page to review the app as deployed to Azure.
Enable continuous deployment
Each time your Docker image is updated, you want the app to receive the update. To do this, you need to enable continuous deployment for the web app service.
Continuous deployment works through a webhook on the registry, and the webhook signs in with the web app’s publishing credentials, which are turned off for new apps. In the web app, go to Settings > Configuration. On the General settings tab, select SCM Basic Auth Publishing Credentials and click Apply.
Next, go to Deployment > Deployment Center. On the Containers tab, select Continuous deployment for the main container and click Apply.
With continuous deployment selected, the web app will trigger a new deployment of the Laravel application each time the Docker image is rebuilt on the Azure container registry.
Automating the deployment
In this step, you will add the pipeline configuration for CircleCI. This pipeline automates testing and runs the commands that build and push the container image to the Azure container registry.
At the root of your project, open the .circleci/config.yml file. Update its content as shown here:
version: 2.1
orbs:
docker: circleci/docker@4.0.1
jobs:
build-and-test:
description: Setup laravel application and run tests
docker:
# Specify the version you desire here
- image: cimg/php:8.5
steps:
- checkout
- run:
name: "Prepare environment"
command: |
sudo apt update
# Download and cache dependencies
- restore_cache:
keys:
# "composer.lock" can be used if it is committed to the repo
- v1-dependencies-{{ checksum "composer.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run:
name: "Install dependencies"
command: composer install -n --prefer-dist
- save_cache:
key: v1-dependencies-{{ checksum "composer.json" }}
paths:
- ./vendor
- run:
name: "Create .env file and generate app key"
command: |
mv .env.example .env
php artisan key:generate
- run:
name: "Run tests"
command: php vendor/bin/phpunit
build-docker-image:
executor:
name: docker/docker
tag: "3.13"
steps:
- checkout
- setup_remote_docker:
docker_layer_caching: true
- run:
name: "Build and push Docker image"
command: |
docker build -t $REGISTRY/laravelapidocker:latest .
echo $DOCKER_PASS | docker login $REGISTRY -u $DOCKER_USER --password-stdin
docker push $REGISTRY/laravelapidocker:latest
workflows:
test-and-deploy:
jobs:
- build-and-test
- build-docker-image:
requires:
- build-and-test
Here is a breakdown of the configuration.
The CircleCI configuration always starts with the version. For this tutorial, you are using version 2.1.
The next part of the configuration specifies two different jobs:
build-and-testbuild-docker-image
The build-and-test job uses the CircleCI PHP 8.5 Docker image, checks out your project from GitHub, installs the project’s dependencies, sets up the environment variables, and runs the application’s tests.
The build-docker-image job creates a Docker image for the code pulled from the GitHub repository and updates the Azure container registry with the latest version of the container. It reads the registry’s login server and the token credentials from the REGISTRY, DOCKER_USER, and DOCKER_PASS environment variables, so you don’t need to edit the configuration for your own registry. setup_remote_docker runs Docker commands in a separate remote environment, and docker_layer_caching reuses unchanged image layers between runs. Docker layer caching costs extra credits per job run, so you can remove that line if you prefer. The requires key specifies that the build-docker-image does not run until the build-and-test job is complete.
Connecting the application to CircleCI
Now you need to set up a repository on GitHub and link the project to CircleCI. Review Pushing a project to GitHub for instructions.
Log into your CircleCI account. Go to Projects and click Create Project. Name the project docker-laravel-api and click Next. Keep the suggested pipeline name, select your docker-laravel-api repository, and keep the All pushes trigger, which runs a pipeline each time you push to GitHub. Click Next.
CircleCI detects the existing .circleci/config.yml file in your repository. Click Next, review the summary, and click Go to project. If your organization still uses the older GitHub OAuth integration, the steps are slightly different; review Create a project in the CircleCI docs.
Push a commit to start your first workflow.
The build-docker-image job will fail because you have not yet provided your Azure container registry details.
To fix that, you will need to add environment variables for the registry and its token. Click Settings, then Environment Variables. Click Add to create each of these variables:
- The
REGISTRYvariable is the login server of your container registry. - The
DOCKER_USERvariable is the name of the token you created for the container registry. - The
DOCKER_PASSvariable is the token password.
Go back to the workflow. Click Rerun, then Rerun workflow from start.
This time, your workflow will run successfully.
Now you can make changes to the codebase locally and push it to GitHub using continuous deployment.
Conclusion
And there you have it. Using Docker, CircleCI, and Microsoft Azure you were able to automate the deployment process of a Laravel application. You performed the set-up process to ensure that, each time you update the project and push the changes to GitHub, CircleCI will use the configuration details to build a new container image and update the associated Azure container registry. And with continuous deployment enabled on the Azure web app, a webhook resource will be fired to push a new version of the container image to the web app.
I hope that you found this tutorial helpful. Check here for the complete source code of the project you built.