Jenkins Declarative Pipeline with Docker
Use your Docker Build and Run Knowledge
docker build - you can use sh 'docker build . -t <tag>'
in your pipeline stage block to run the docker build command. (Make sure you have docker installed with correct permissions.
docker run: you can use sh 'docker run -d <image>'
in your pipeline stage block to build the container.
How will the stages look:
stages {
stage('Build') {
steps {
sh 'docker build -t trainwithshubham/django-app:latest'
}
}
}
Task-01
🔹Create Declarative Pipeline with Docker
Install the required plugins to inject the docker hub credentials to set an environment for the builds.
From the Jenkins dashboard, click on "New Item" to create a new project.
Enter a project name and select "Pipeline" Click "OK" to create the project.
Under the Configuration, Select the GitHub Project checkbox -> Enter the URL and Enabled the GitHub hook trigger for GITScm polling.
GitHub WebHooks Setup:
Accessed my repository on GitHub and go to Settings -> Webhooks
Added a new webhook with my Jenkins job's URL Selected events to trigger (e.g., push, pull request).
Saved the webhook.
Create Environment variable credential for docker hub:
Click on "manage jenkins" > Credentials.
Click on "Systum" > "Global Credentials(unrestricted)" > "Add Credentials".
Add the docker hub credentials and click on create
Running the Application:
Install docker and docker-compose on the server. Add the current user to the
docker
group:sudo usermod -aG docker $USER sudo reboot
Add the Jenkins user to the
docker
group:sudo usermod -aG docker jenkins sudo systemctl restart jenkins
Inside the Dashboard "Node-app" job > Within the Jenkins job's Pipeline build step.
pipeline { agent any stages{ stage('Clone Code'){ steps { echo "Cloning the code" git url:"https://github.com/ajaygite/node-todo-app.git", branch:"master" } } stage('Build'){ steps { echo "Building the Image" sh "docker build -t todo-app ." } } stage('push to dockerhub'){ steps { echo "Pushing the code to dockerhub" withCredentials([usernamePassword(credentialsId:"dockerhub",passwordVariable:"dockerHubPass",usernameVariable:"dockerHubUser")]){ sh "docker tag todo-app ${env.dockerHubUser}/node-app:latest" sh "docker login -u ${env.dockerHubUser} -p ${env.dockerHubPass}" sh "docker push ${env.dockerHubUser}/node-app:latest" } } } stage('Deploy'){ steps { echo "Deploying the application" sh "docker-compose down" sh "docker-compose up -d --build" } } } }
Save and click on Build Now.
Once done hit the URL http://ipaddress:8000 to check if it is running.
Subscribe to my newsletter
Read articles from Ajay Gite directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by