Question

Deploying a Laravel Application with Docker on Git PR Merge Commits using Jenkins

Hey all,

Today, I’ll talk about how to automate your Laravel Application to be deployed with Docker by CI/CD - Jenkins on Github PR merges.

Laravel is a popular PHP web application framework, and Docker is a platform that simplifies application deployment using containers. Combining these two technologies with Jenkins can create a powerful CI/CD pipeline. In this mini-tutorial, we will guide you through setting up a Jenkins job that deploys your Laravel application with Docker whenever a pull request (PR) is merged into your Git repository.


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
May 8, 2023
Accepted Answer

Prerequisites:

In this mini-tutorial, I’ll assume you have a Laravel Application and Jenkins server configured however if you don’t have anything, I’ll recommend checking our MarketPlace for a Laravel ready Droplet:

https://marketplace.digitalocean.com/apps/laravel

Additionally, if you want to have your Database Managed, you can check the following:

https://docs.digitalocean.com/products/databases/mysql/

For Jenkins, you can follow this tutorial:

https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-20-04

Lastly, to configure Docker if needed, you can follow this tutorial:

https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-compose-on-ubuntu-22-04

Configure Jenkins Job

Navigate to the Jenkins dashboard and create a new job. Choose “Pipeline” and provide a unique name for the job.

Navigate to the “Pipeline” section and select “Pipeline script from SCM” in the “Definition” field. Choose “Git” as your SCM and provide your repository URL and credentials as needed.

To trigger the build on PR merge commits, you can use the “GitHub hook trigger for GITScm polling” option. First, install the “GitHub Integration” plugin in Jenkins, then navigate to the “Build Triggers” section and check the “GitHub hook trigger for GITScm polling” box.

Next, configure a webhook in your GitHub repository. In your repository settings, go to “Webhooks” and click on “Add webhook.” Set the “Payload URL” to http://your-jenkins-url/github-webhook/ and select “Let me select individual events.” Check the “Pull requests” event and save the webhook.

Write the Jenkins Pipeline Script

In the “Pipeline” section, add the following Groovy script to the “Script Path” field:

pipeline {
    agent any

    environment {
        GIT_COMMIT_SHORT = "${sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()}"
    }

    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'your-repository-url'
            }
        }

        stage('Create Dockerfile') {
            steps {
                writeFile file: 'Dockerfile', text: '''
FROM php:7.4-fpm

# Install required extensions and dependencies
RUN apt-get update && apt-get install -y \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libzip-dev \
    unzip \
    git \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install pdo_mysql zip

# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www/html

# Copy application files
COPY . /var/www/html

# Install dependencies
RUN composer install --no-interaction --no-dev --optimize-autoloader

# Set permissions
RUN chown -R www-data:www-data /var/www/html/storage
RUN chown -R www-data:www-data /var/www/html/bootstrap/cache
'''
            }
        }

        stage('Build Docker Image') {
            steps {
                sh "docker build -t your-dockerhub-username/your-image-name:${env.GIT_COMMIT_SHORT} ."
            }
        }

        stage('Push Docker Image') {
            steps {
                withCredentials([string(credentialsId: 'your-dockerhub-credentials-id', variable: 'DOCKERHUB_TOKEN')]) {
                    sh "echo '${DOCKERHUB_TOKEN}' | docker login -u your-dockerhub-username --password-stdin"
                    sh "docker push your-dockerhub-username/your-image-name:${env.GIT_COMMIT_SHORT}"
                }
            }
        }

        stage('Deploy Laravel Application') {
            steps {
                // Replace 'ssh-credentials-id' with your SSH credentials ID in Jenkins
                sshagent(['ssh-credentials-id']) {
                    // Replace 'your-deployment-server' with your server's IP or domain
                    sh "ssh your-deployment-server 'docker pull your-dockerhub-username/your-image-name:${env.GIT_COMMIT_SHORT}'"
                    sh "ssh your-deployment-server 'docker-compose down && docker-compose up -d --force-recreate'"
                }
            }
        }
    }

    post {
        failure {
            // Configure notifications if required, e.g., email, Slack, etc.
        }
    }
}

This script defines a pipeline with the following stages:

  1. Checkout: Clone the Git repository and switch to the main branch.
  2. Create Dockerfile: Generate a Dockerfile directly within the Jenkins job, containing the necessary instructions to build a Docker image for your Laravel application.
  3. Build Docker Image: Build the Docker image using the created Dockerfile and tag the image with the short Git commit hash.
  4. Push Docker Image: Push the built image to Docker Hub using your credentials.
  5. Deploy Laravel Application: Connect to your deployment server via SSH, pull the latest Docker image using the Git commit hash, and then use docker-compose to recreate the services.

Make sure to replace the placeholders (e.g., your-repository-url, your-dockerhub-username, your-image-name, your-dockerhub-credentials-id, ssh-credentials-id, and your-deployment-server) with your own values.

Test the Pipeline

Create a pull request and merge it in your Git repository. The Jenkins job should trigger automatically and execute the pipeline, deploying your Laravel application using Docker.

Conclusion

You have now successfully created a Jenkins job that deploys your Laravel application with Docker on Git PR merge commits. With this CI/CD pipeline, your development team can streamline the deployment process and ensure that your application stays up-to-date with the latest changes.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel