Laravel CI/CD Pipeline: Easy GitHub, Jenkins, and Docker Step-by-Step Guide (5 Step)

Streamlining Laravel Deployment with GitHub, Jenkins, and Docker: A Comprehensive Guide to CI/CD Pipelines

Topics: Laravel, CI/CD Pipeline, Continuous Deployment, Jenkins, Docker, DevOps, PHP Development, Automation


Introduction

Continuous Integration and Continuous Deployment (CI/CD) pipelines optimize software development by automating code testing and deployment. This guide provides step-by-step instructions for setting up a Laravel CI/CD pipeline using GitHub, Jenkins, and Docker. From Dockerizing your Laravel application to automating builds, tests, and deployments, you’ll learn how to achieve a seamless delivery process.

Prerequisites

  1. GitHub Account: To store your code and manage the repository.
  2. Jenkins: For Continuous Integration and Deployment automation.
  3. Docker: To containerize the Laravel application for consistent environments.
  4. Laravel Project: A Laravel application you want to deploy.

1. Setting Up the Laravel Application (Project Setup)

Assume you have a Laravel project stored in a GitHub repository. Here’s a quick guide on how to get started with Laravel.

  1. Install Laravel via Composer:
    composer create-project --prefer-dist laravel/laravel your-project-name
  2. Push your Laravel project to GitHub:
    git init
    git add .
    git commit -m "Initial commit"
    git remote add origin https://github.com/yourusername/your-repo.git
    git push -u origin master

2. Dockerizing the Laravel Application

Next, we will Dockerize the Laravel application by creating a Dockerfile and docker-compose.yml.

Dockerfile:

Create a Dockerfile in the root directory of your Laravel project:

# Use an official PHP image as the base image
FROM php:8.1-fpm

# Install system dependencies and PHP extensions
RUN apt-get update && apt-get install -y libpng-dev libjpeg-dev libfreetype6-dev zip git 
    && docker-php-ext-configure gd --with-freetype --with-jpeg 
    && docker-php-ext-install gd pdo pdo_mysql

# Set the working directory inside the container
WORKDIR /var/www

# Copy the Laravel project files into the container
COPY . .

# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Install project dependencies
RUN composer install --no-interaction

# Expose port 9000 and start PHP-FPM
EXPOSE 9000
CMD ["php-fpm"]

docker-compose.yml:

Create a docker-compose.yml to define how the Docker containers will work together:

version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: laravel-app
    restart: unless-stopped
    networks:
      - laravel-network
    volumes:
      - .:/var/www
    ports:
      - 8080:9000

  db:
    image: mysql:5.7
    container_name: mysql-db
    restart: unless-stopped
    networks:
      - laravel-network
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_DATABASE: laravel
    volumes:
      - mysql-data:/var/lib/mysql

networks:
  laravel-network:
    driver: bridge

volumes:
  mysql-data:
    driver: local

3. Setting Up Jenkins for CI/CD

  1. Install Jenkins:
    Install Jenkins on a server. You can follow the official documentation to install Jenkins on your preferred system (Ubuntu, macOS, Windows).
  2. Install Necessary Plugins:
    Once Jenkins is installed, you’ll need the following plugins:

    • GitHub Plugin
    • Docker Plugin
    • Pipeline Plugin
  3. Create a Jenkins Pipeline Job:
    • Go to Jenkins Dashboard > New Item > Pipeline.
    • Name your pipeline job (e.g., laravel-ci-cd-pipeline).
    • Select Pipeline and click OK.
  4. Configure GitHub Integration:
    • In the pipeline job configuration, under the Pipeline section, specify the SCM as Git.
    • Add your GitHub repository URL and credentials (if private repository).
  5. Define the Pipeline Script:
    You can write your pipeline directly in Jenkins or use a Jenkinsfile within your project. Below is a sample Jenkinsfile:
pipeline {
    agent any

    environment {
        DOCKER_IMAGE = 'laravel-app'
        REGISTRY = 'docker.io'
        REGISTRY_CREDENTIALS = 'dockerhub_credentials'
    }

    stages {
        stage('Checkout Code') {
            steps {
                // Checkout code from GitHub repository
                git branch: 'main', url: 'https://github.com/yourusername/your-repo.git'
            }
        }

        stage('Build Docker Image') {
            steps {
                script {
                    // Build the Docker image for the Laravel app
                    sh 'docker build -t $DOCKER_IMAGE .'
                }
            }
        }

        stage('Run Tests') {
            steps {
                script {
                    // Run tests inside the Docker container
                    sh 'docker run --rm $DOCKER_IMAGE ./vendor/bin/phpunit'
                }
            }
        }

        stage('Push Docker Image') {
            steps {
                script {
                    // Login to Docker Hub and push the image
                    withCredentials([usernamePassword(credentialsId: 'dockerhub_credentials', usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
                        sh 'echo $DOCKER_PASSWORD | docker login -u $DOCKER_USERNAME --password-stdin'
                    }
                    sh 'docker push $DOCKER_IMAGE'
                }
            }
        }

        stage('Deploy to Server') {
            steps {
                script {
                    // Deploy your Docker container to a production server (using SSH, Kubernetes, etc.)
                    // Example using SSH to deploy
                    sh 'ssh user@yourserver "docker pull $DOCKER_IMAGE && docker-compose up -d"'
                }
            }
        }
    }

    post {
        always {
            // Clean up
            sh 'docker system prune -f'
        }
    }
}

This Jenkinsfile defines the following pipeline stages:

  • Checkout Code: Clones the Laravel project from GitHub.
  • Build Docker Image: Builds the Docker image for the Laravel application.
  • Run Tests: Runs PHPUnit tests inside the Docker container.
  • Push Docker Image: Pushes the Docker image to Docker Hub.
  • Deploy to Server: Deploys the image to the production server using Docker.

4. Setting Up GitHub Webhook

  1. Go to your GitHub repository, and under Settings > Webhooks, add a new webhook.
  2. Set the Payload URL to your Jenkins server’s webhook URL (e.g., http://your-jenkins-server/github-webhook/).
  3. Set Content Type to application/json and choose Just the Push Event.

This ensures that every time you push code to GitHub, Jenkins will trigger the CI/CD pipeline.


5. Testing the Laravel CI/CD Pipeline

  1. Push some changes to the GitHub repository.
  2. Jenkins will automatically trigger the pipeline, execute the stages, and deploy the Dockerized Laravel application.

Conclusion

This setup automates the process of code integration, testing, and deployment for a Laravel CI/CD Pipeline application using GitHub, Jenkins, and Docker. You can extend this pipeline with more stages like linting, security scanning, or notifications based on your project needs. This approach ensures consistency and reliability in your deployment process, and Docker provides the application runs the same in all environments.


DoFollow Links

Stay Connected!

  • Connect with me on LinkedIn to discuss ideas or projects.
  • Check out my Portfolio for exciting projects.
  • Give my GitHub repositories a star ⭐ on GitHub if you find them useful!

Your support and feedback mean a lot! 😊

If you need any support regarding your website

If you like our blog, Please support us to improve

Buy Me a Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *

RECENT POST
Leetcode Solutions

633. Sum of Square Numbers

Sum of Square Numbers Difficulty: Medium Topics: Math, Two Pointers, Binary Search Given a non-negative integer c, decide whether there’re

Leetcode Solutions

624. Maximum Distance in Arrays

Maximum Distance in Arrays Difficulty: Medium Topics: Array, Greedy You are given m arrays, where each array is sorted in

Leetcode Solutions

592. Fraction Addition and Subtraction

Fraction Addition and Subtraction Difficulty: Medium Topics: Math, String, Simulation Given a string expression representing an expression of fraction addition