
Hello Readers, In this we are going to learn How to Build and Push a Docker Image using JenkinsFile Before you start you must have installed and configured docker and Jenkins on your system.
What is Docker?
Docker is an open platform for developers and system administrators to build, ship, and run decentralized applications.
To learn more about docker you can check this URL
Why do we need Jenkins-Pipeline?
You can reuse everything you’ve done and paste your Jenkins code into your git project. Changes to the pipeline appear in Job History Changes.
What’s DockerHub?
Dockerhub is a public Docker registry for storing Docker images. If you wish to register as an individual, you can pay. Use this because it is the simplest Docker registry.
Now, let’s create a sample python app :
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
you can run the python app using the command:
python3 app.py
Now, create a dockerfile to dockerize the project:
FROM python:3.8-alpine
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
Once you have the Jenkinsfile created, create a Github repo and push the entire project to the repo.
pipeline{
agent any
options{
buildDiscarder(logRotator(numToKeepStr: '5', daysToKeepStr: '5'))
timestamps()
}
environment{
registry = "<dockerhub-username>/<repo-name>"
registryCredential = '<dockerhub-credential-name>'
}
stages{
stage('Building image') {
steps{
script {
dockerImage = docker.build registry + ":$BUILD_NUMBER"
}
}
}
stage('Deploy Image') {
steps{
script {
docker.withRegistry( '', registryCredential ) {
dockerImage.push()
}
}
}
}
}
Now you can start working on Jenkins and building your project. It is assume that the Jenkins server is already install and running. First, let’s add Dockerhub credentials to Jenkins. These credentials are used to log in to Dockerhub. Click Manage Jenkins, then click Manage Credentials.



Click global, then Add Credentials to add a new credential with a Global Scope.



Add your Dockerhub username and password. The ID is used in the Jenkinsfile and stores the credentials. You can see this used in the Jenkinsfile.
Now the pipeline is ready to be created. Go back to the dashboard and select New Item. Now, Enter a name for the new item, select Pipeline, and click OK.



Enter a Display Name for the pipeline.



Enter the Github repo URL and click Validate



Under Pipeline leave the default Jenkinsfile because this will look for the Jenkinsfile in the cloned repo.
That’s it, click save and the project should begin running immediately.



The project will take a few minutes to run, but the initial output should look similar to mine.
Now, you have a pipeline to create and push a docker image for your application.
Reference:
https://www.jenkins.io/doc/book/pipeline/docker/