0
0
JenkinsHow-ToBeginner · 4 min read

How to Run Docker Compose in Jenkins: Step-by-Step Guide

To run docker compose in Jenkins, ensure the Jenkins agent has Docker and Docker Compose installed and configured. Use a Jenkins pipeline step with sh 'docker compose up -d' to start your services inside a shell script block.
📐

Syntax

The basic syntax to run Docker Compose in Jenkins pipeline is:

  • sh 'docker compose [options]': Runs Docker Compose commands in a shell.
  • docker compose up -d: Starts containers in detached mode.
  • Ensure Jenkins user has permission to run Docker commands.
groovy
pipeline {
  agent any
  stages {
    stage('Run Docker Compose') {
      steps {
        sh 'docker compose up -d'
      }
    }
  }
}
💻

Example

This example shows a Jenkins pipeline that runs docker compose up -d to start services defined in a docker-compose.yml file located in the workspace.

groovy
pipeline {
  agent any
  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }
    stage('Start Services') {
      steps {
        sh 'docker compose up -d'
      }
    }
  }
}
Output
Creating network "project_default" with the default driver Creating service1 ... done Creating service2 ... done
⚠️

Common Pitfalls

Common mistakes when running Docker Compose in Jenkins include:

  • Jenkins user lacks permission to run Docker commands. Fix by adding Jenkins user to the docker group.
  • Docker Compose not installed or using old docker-compose binary instead of the new docker compose CLI.
  • Running commands outside the workspace where docker-compose.yml is located.
  • Not using -d flag causing the pipeline to hang.
bash
/* Wrong: No permissions */
sh 'docker compose up -d'

/* Fix: Add Jenkins user to docker group and restart Jenkins agent */
📊

Quick Reference

Tips for running Docker Compose in Jenkins:

  • Install Docker and Docker Compose on Jenkins agents.
  • Use sh 'docker compose up -d' inside pipeline steps.
  • Ensure Jenkins user has Docker permissions.
  • Keep docker-compose.yml in the workspace root.
  • Use docker compose down to stop services after tests.

Key Takeaways

Ensure Jenkins agents have Docker and Docker Compose installed and configured.
Run Docker Compose commands inside sh steps in Jenkins pipelines.
Add Jenkins user to the Docker group to avoid permission errors.
Keep your docker-compose.yml file in the Jenkins workspace directory.
Use detached mode -d to prevent pipeline hanging during service startup.