Hey Learners! Welcome back. In the previous task, we created a simple project to print "Hello World!!" using the declarative pipeline, now it's time to level up things. Let's integrate the Docker with the Jenkins declarative pipeline.
We discussed in earlier tasks about docker build and docker run commands, let's learn how to use them in declarative pipelines
Docker Build:- You can use this command in the declarative pipeline as
sh 'docker build -t <any-name-for-image> .
Docker run:- Use
sh 'docker run -d --name <container-name-any> <image-name>
this command in your pipeline.The above commands should be used in pipeline stages as shown below
pipeline { agent any stages { stage('Build') { steps { sh 'docker build -t trainwithshubham/django-app:latest' } } } }
Task 1-
In this task, we will create the declarative pipeline for the same project as we did in the Day24 task. Click here to see.
Create a new job and select pipeline.
Add a description if want then scroll down to the pipeline section and write pipeline as shown and then save the job.
pipeline { agent any stages { stage('Clone'){ steps { git 'https://github.com/amitvpawar/Day24ProjectNodeJSTo-Do-App.git' } } stage('Build'){ steps { sh 'docker build -t day27todoapp .' } } stage('Run'){ steps { sh 'docker run -d --name day27container -p 8001:8000 day27todoapp' } } } }
Build a job and see the console output as well.
Access your application on the browser as shown below
It's working. Now if we run the job again it will fail because Jenkins tries to build a container but as we already have a running container with the same name and the same exposed port, creates a conflict. To see this click on build now and see the console output. Ref below screenshot
To overcome this we use a docker-compose configuration file. Let's look at how to create a project of docker-compose with declarative pipelines in the next task.
Task 2-
We already have a docker-compose.yml configuration file in our repository, so we have to use docker-compose commands to up and down the service containers.
Note:- Make sure the correct image is specified in your docker-compose.yml conf file. I am using the default con file for the demo.
You can create one more project or just change the existing pipeline as shown below
stage('Run'){
steps {
sh '''docker-compose down
docker-compose up -d'''
}
}
Use the above 'Run' instead of the previous one.
Note:- If you are making changes with the existing one make sure you delete all the previously created docker containers.
Access your application but this time on port 8000. (Hope you get why port 8000)
This is how we create declarative pipelines in Jenkins.
Thank you so much for taking the time to read till the end! Hope you found this blog informative.
Feel free to explore more of my content, and don't hesitate to reach out if need any assistance from me or in case of you have any questions.
Find me on:- Hashnode LinkedIn Github
Happy Learning!