Table of Contents


Prerequisites

Step 1 — Prepare the source code VM

Clone the GitLab project and create a bare repository that will act as the push target:

# set config
git config --global user.name "Your Name"
git config --global user.email "name@domain.example"
git config --global init.defaultBranch main
 
# Create a bare repo
sudo mkdir -p /mnt/webcounter.git
sudo chmod 777 /mnt/webcounter.git
cd /mnt/webcounter.git
git init --bare
 
# clone the project from GitLab
cd /home/redhat
git clone https://gitlab.com/form-cfreire/webcounter.git
cd webcounter
 
# create a bare repo on the VM that will receive pushes
git remote add origin docker-cfreire-workstation:/mnt/webcounter.git
 

The bare repository at /mnt/webcounter.git is what developers push to; its post-receive hook triggers Jenkins.

Step 2 — Grant the Swarm manager SSH access to the source VM

The Jenkins agent runs on the Swarm manager and must be able to reach the source VM over SSH (to check out the code). Generate a key on the manager and authorize it on the source VM:

Add ssh-key to Jenkins

Step 3 — Add the Jenkinsfile

Create a Jenkinsfile in the root of the webcounter project and push it to the repo:

// Jenkinsfile — CI/CD for the webcounter project
pipeline {
    agent { label 'linux' }
 
    environment {
        // where the source lives (on the source VM)
        SRC_HOST  = "ec2-user@[SOURCE_VM_IP]"
        SRC_PATH  = "~/webcounter"
        // Docker Hub image
        IMAGE     = "<docker_id>/webcounter"
        // stack name and compose file
        STACK     = "webcounter"
    }
 
    stages {
        stage('Checkout') {
            steps {
                // pull the latest code from the source VM
                sh "rsync -az --delete ${SRC_HOST}:${SRC_PATH}/ ${WORKSPACE}/"
            }
        }
 
        stage('Test') {
            steps {
                // simple smoke test: the app must be valid Python
                sh "python3 -m compileall ."
            }
        }
 
        stage('Build image') {
            steps {
                sh "docker build -t ${IMAGE}:${BUILD_NUMBER} -t ${IMAGE}:latest ."
            }
        }
 
        stage('Push image') {
            steps {
                // credentials 'dockerhub' = Docker Hub username + password (Secret text)
                withCredentials([string(credentialsId: 'dockerhub', variable: 'DH_TOKEN')]) {
                    sh 'echo "$DH_TOKEN" | docker login -u <docker_id> --password-stdin'
                }
                sh "docker push ${IMAGE}:${BUILD_NUMBER}"
                sh "docker push ${IMAGE}:latest"
            }
        }
 
        stage('Deploy to Swarm') {
            steps {
                sh "docker stack deploy --compose-file docker-compose.yml --with-registry-auth ${STACK}"
            }
        }
    }
 
    post {
        success { echo "Deployed ${STACK} — build ${BUILD_NUMBER}" }
        failure { echo "Pipeline failed for ${STACK} — build ${BUILD_NUMBER}" }
        always  { sh "docker logout" }
    }
}

Why rsync instead of git clone

The pipeline keeps the working copy on the source VM and syncs it into the Jenkins workspace. Alternatively, configure the Jenkins job’s SCM section to check out ssh://ec2-user@[SOURCE_VM_IP]/~/webcounter.git directly — the rsync approach keeps the lab simpler.

The stack uses the same docker-compose.yml from 03-docker-swarm:

---
services:
 
  redis:
    image: "redis:alpine"
 
  webcounter:
    image: "<docker_id>/webcounter:latest"
    ports:
      - 80:5000
    environment:
      - REDIS_URL=redis
    depends_on:
      - redis
    deploy:
      mode: replicated
      replicas: 3
      resources:
        limits:
          cpus: "0.2"
          memory: 128M
      restart_policy:
        condition: on-failure

Step 4 — Create the Jenkins pipeline job

  1. Dashboard → New Item → type Pipeline, name it webcounter-cicd.
  2. In Pipeline section, set Definition: Pipeline script from SCM — or paste the Jenkinsfile content directly for the first run.
  3. If using SCM: set the git URL to the SSH path on the source VM (ssh://ec2-user@[SOURCE_VM_IP]/~/webcounter.git) and add the SSH key in Credentials.
  4. Make sure the agent label matches the pipeline (linux) — use the Swarm manager node as the agent so it can run docker build and docker stack deploy.

Docker permissions for the agent

The Jenkins agent user must be in the docker group on the manager to run docker build, docker push and docker stack deploy without sudo.

Step 5 — Create the user token and build token

Remote builds need two tokens:

  1. User token — Jenkins UI: user → Configure → API Token → add new.
  2. Build token — any string, e.g. generated with date | md5sum.

Configure the job: Pipeline → Build when a change is pushed to Git (or Trigger builds remotely in Freestyle) → set the build token.

Test the remote trigger manually first:

$ curl -X POST -u "admin:<USER_TOKEN>" \
    "http://[JENKINS_IP]:8080/job/webcounter-cicd/build?token=<BUILD_TOKEN>"

Jenkins should start a build — verify on the dashboard and in the console output.

Step 6 — Configure the post-receive hook

On the source VM, create the hook in the bare repository:

~/webcounter.git/hooks/post-receive

#!/bin/sh
# trigger Jenkins CI/CD on every push
echo "Trigger build"
curl -s -X POST \
  -u "admin:<USER_TOKEN>" \
  "http://[JENKINS_IP]:8080/job/webcounter-cicd/build?token=<BUILD_TOKEN>"
echo "Done!"

Make it executable:

chmod +x ~/webcounter.git/hooks/post-receive

Step 7 — Test the full CI/CD flow

Push a small change to the project:

cd webcounter
# ... edit source ...
git add . && git commit -m "test CI/CD trigger" && git push origin main

Then verify each stage:

  1. The hook fires on the source VM (curl output appears on push).
  2. Jenkins dashboard shows a new build for webcounter-cicd.
  3. The console output shows all stages completing: Checkout → Test → Build → Push → Deploy.
  4. On the Swarm manager, the stack is updated:
$ docker stack ps webcounter
ID             NAME                  IMAGE                        NODE      DESIRED STATE   CURRENT STATE
x1y2z3         webcounter_webcounter.1  <docker_id>/webcounter:N  node1     Running         Running 10 seconds ago
  1. The app answers on port 80:
$ curl localhost:80
This page has been visited 1 times.

Troubleshooting

SymptomPossible causeFix
Push succeeds but Jenkins never buildsWrong token or job name in the hookCheck the curl URL and both tokens; test the curl manually
docker build fails in pipelineAgent user lacks docker permissionsAdd the agent user to the docker group on the manager
SSH/rsync stage failsKey not authorized on source VMRe-run ssh-copy-id; test ssh ec2-user@[SOURCE_VM_IP] from the manager
docker push deniedDocker Hub credentials missing/expiredRe-create the dockerhub credential in Jenkins
Stack not updated after deployImage tag not changedConfirm the pipeline pushes :latest and the compose file uses it

Cleanup

Destructive commands

The following remove the stack and its containers.

# remove the deployed stack
docker stack rm webcounter
 
# stop Jenkins (if desired)
docker stack rm jenkins
 
# remove pulled/built images
docker rmi <docker_id>/webcounter:latest redis:alpine

Terminate the EC2 instances when done with the lab.