Automate build, package and push with Jenkins pipelines as code
git push → CI server (Jenkins) → Build → Test → Package Docker image → Push to registry → Deploy
git push
Goal: a shorter development lifecycle — the machine does the repetitive steps, the same way every time.
Jenkinsfile
jenkins/compose.yaml builds a custom image on top of jenkins/jenkins:jdk25:
jenkins/compose.yaml
jenkins/jenkins:jdk25
services: jenkins: container_name: jenkins build: dockerfile_inline: | FROM jenkins/jenkins:jdk25 # + maven, docker-ce, kubectl, AWS CLI RUN usermod -aG docker jenkins ports: - 9080:8080 volumes: - ${CONFIG:-./config}/jenkins:/var/jenkins_home - /var/run/docker.sock:/var/run/docker.sock
docker compose up -d --build # then open http://localhost:9080/
Mounting /var/run/docker.sock gives the container full control of the host Docker daemon. OK locally; harden it (rootless Docker, dedicated build daemon) when shared.
/var/run/docker.sock
On first start Jenkins asks for a random initial admin password:
docker logs jenkins 2>&1 | grep -A 3 "initialAdminPassword" docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
An executor is a slot that runs one job. More executors → several microservices built in parallel. On Windows, open the terminal as Administrator.
Manage Jenkins → Credentials → System → Global credentials → Add Credentials
dockerhub-credential
Use a token with Read & Write scope, not your password: a leaked token is revoked without touching the account.
account
pipeline { agent any stages { stage('Build') { steps { sh 'mvn -B -DskipTests clean install' } } } }
-B
account-service
environment { SERVICE = 'account' NAME = "humbertosandmann/${env.SERVICE}" }
build job: 'account', wait: true
mvn -B -DskipTests clean package
NAME is the Docker Hub repository; replace the user with yours.
NAME
withCredentials([usernamePassword( credentialsId: 'dockerhub-credential', usernameVariable: 'USERNAME', passwordVariable: 'TOKEN')]) { sh 'echo $TOKEN | docker login -u $USERNAME --password-stdin' sh "docker buildx create --use --platform=linux/arm64,linux/amd64 ..." sh "docker buildx build --platform=linux/arm64,linux/amd64 --push \ --tag ${env.NAME}:latest --tag ${env.NAME}:${env.BUILD_ID} -f Dockerfile ." sh "docker buildx rm --force multi-platform-builder-${env.SERVICE}" }
withCredentials
$TOKEN
buildx
linux/arm64
linux/amd64
:latest
:<BUILD_ID>
credentialsId
build job: 'account'
-DskipTests
Test
mvn test
docker buildx
latest
BUILD_ID
Outline: (1) CI and CD; (2) Jenkins in a container; (3) unlock, executors, credentials; (4) Jenkinsfile: build-only and build-package-push; (5) pitfalls.
The executors point: account-service occupies a slot while it waits for account.