Table of Contents
- Prerequisites
- Step 1 — Prepare the source code VM
- Step 2 — Grant the Swarm manager SSH access to the source VM
- Step 3 — Add the Jenkinsfile
- Step 4 — Create the Jenkins pipeline job
- Step 5 — Create the user token and build token
- Step 6 — Configure the post-receive hook
- Step 7 — Test the full CI/CD flow
- Troubleshooting
- Cleanup
Prerequisites
- A running Docker Swarm (3 managers, see 03-docker-swarm).
- Jenkins running on the Swarm (setup covered in 01-jenkins-jump-start; it is assumed here).
- A Docker Hub account and an SSH key pair.
- The GitLab project: https://gitlab.com/form-cfreire/webcounter (Python web counter with a Redis backend).
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 JenkinsStep 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.gitdirectly — 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-failureStep 4 — Create the Jenkins pipeline job
- Dashboard → New Item → type Pipeline, name it
webcounter-cicd. - In Pipeline section, set Definition: Pipeline script from SCM — or paste the Jenkinsfile content directly for the first run.
- 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. - Make sure the agent label matches the pipeline (
linux) — use the Swarm manager node as the agent so it can rundocker buildanddocker stack deploy.
Docker permissions for the agent
The Jenkins agent user must be in the
dockergroup on the manager to rundocker build,docker pushanddocker stack deploywithout sudo.
Step 5 — Create the user token and build token
Remote builds need two tokens:
- User token — Jenkins UI: user → Configure → API Token → add new.
- 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-receiveStep 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 mainThen verify each stage:
- The hook fires on the source VM (
curloutput appears on push). - Jenkins dashboard shows a new build for
webcounter-cicd. - The console output shows all stages completing: Checkout → Test → Build → Push → Deploy.
- 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- The app answers on port 80:
$ curl localhost:80
This page has been visited 1 times.Troubleshooting
| Symptom | Possible cause | Fix |
|---|---|---|
| Push succeeds but Jenkins never builds | Wrong token or job name in the hook | Check the curl URL and both tokens; test the curl manually |
docker build fails in pipeline | Agent user lacks docker permissions | Add the agent user to the docker group on the manager |
| SSH/rsync stage fails | Key not authorized on source VM | Re-run ssh-copy-id; test ssh ec2-user@[SOURCE_VM_IP] from the manager |
docker push denied | Docker Hub credentials missing/expired | Re-create the dockerhub credential in Jenkins |
| Stack not updated after deploy | Image tag not changed | Confirm 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:alpineTerminate the EC2 instances when done with the lab.