In today's fast-paced world of software development, the need for automation in building, testing, and deploying applications is more critical than ever. Continuous Integration (CI) and Continuous Deployment (CD) pipelines play a key role in streamlining these processes. In this blog post, we'll explore a Jenkins pipeline written in Groovy that leverages Docker to automate these tasks seamlessly.
Jenkins Pipeline Overview:
Our Jenkins pipeline consists of several stages, each serving a specific purpose:
Code Stage:
groovyCopy codestage('code') {
steps {
git url: 'https://github.com/muhammadhassanb111/node-todo-cicd.git', branch: 'master'
}
}
In this stage, we fetch the latest code from our GitHub repository, ensuring that we're always working with the most up-to-date version of our application.
Build and Test Stage:
groovyCopy codestage('build and test') {
steps {
script {
echo '=== Building Docker Image ==='
sh 'docker build . -t hassanb111/node-todo-app:latest'
echo '=== Docker Image Built ==='
echo '=== Docker Images List ==='
sh 'docker images'
echo '=== End of Docker Images List ==='
}
}
}
In this stage, we build a Docker image from our application's Dockerfile. The process is accompanied by informative messages, and we list the Docker images for visibility.
Login and Push Images Stage:
groovyCopy codestage('login and push images') {
steps {
echo 'Logging into Docker Hub'
withCredentials([usernamePassword(credentialsId: 'dockerhub', passwordVariable: 'dockerhubpassword', usernameVariable: 'dockerhubuser')]) {
sh "docker login -u ${env.dockerhubuser} -p ${env.dockerhubpassword}"
sh "docker push hassanb111/node-todo-app:latest"
}
}
}
This stage handles the secure login to Docker Hub using Jenkins credentials and subsequently pushes the Docker image to the Docker Hub repository.
Deploy Stage:
groovyCopy codestage('deploy') {
steps {
script {
echo '=== Stopping and Removing Containers ==='
sh 'docker-compose down'
echo '=== Containers Stopped and Removed ==='
echo '=== Starting Containers ==='
sh 'docker-compose up -d'
echo '=== Containers Started ==='
}
}
}
The final stage involves stopping and removing existing Docker containers and then initiating fresh containers using Docker Compose.




By breaking down our CI/CD process into these stages, we ensure a systematic and automated approach to software development. This Jenkins pipeline, combined with Docker, provides a powerful foundation for building, testing, and deploying applications efficiently.