Wednesday, April 25, 2018

How to automate Docker image creation by using Jenkins Pipeline

Every time developer makes changes to the code, you would want to Jenkins to automate Docker images creation and pushing into Docker registry. Let us see how to do this.

Pre-requisites:

Jenkins up and running
Docker plug-in installed in Jenkins

Port - 4243 open in AWS security firewall for EC2
port - 8085 - Container will be listening to

Steps:

1. Change the default configuration of docker and make below chnages.

sudo vi /lib/systemd/system/docker.service
Modify the below line like highligthed yellow:
ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:4243








2. Also make the below change as well
sudo vi /etc/init.d/docker
DOCKER_OPTS="-H tcp://0.0.0.0:4243"





3. Add jenkins user to Docker group.
sudo usermod -a -G docker jenkins

4. sudo service jenkins restart

5. sudo systemctl daemon-reload
6. sudo service docker stop
7. sudo service docker start
8. click Jenkins,  Credentials, Global and Add credentials
enter username and password of Docker Cloud registry and save.
9. Create a pipeline.
10. Enable Poll SCM or Webhooks
11. Copy paste the below code for Pipeline code

node {
   
    def image
    stage ('checkout') {
     // copy the code after generating from Snippet Generator by entering your Git URL and password
    }
   
    stage ('Build') {
       sh "mvn -U clean install -f MyWebApp/pom.xml"
       }
   
    stage ('Code Quality') {
       sh "mvn -U -f MyWebApp/pom.xml sonar:sonar"
       }

    stage ('Docker image build and push') {
    // Build and push image with Jenkins' docker-plugin
    withDockerServer([uri: "tcp://localhost:4243"]) {
      withDockerRegistry([credentialsId: "<credentials_id>", url: "https://index.docker.io/v1/"]) {
        // we give the image the same version as the .war package
        image = docker.build("<docker_cloud_user_id>/mywebapp", "MyWebApp")
        image.push()
      }  
    }
}

  stage('Run Docker Container') {
        image.run("-p 8085:8085 --rm --name myfirstApp")
    }
}

1 comment:

  1. Learn how Docker helps developers bring their ideas to life by conquering the complexity of app development.... Docker

    ReplyDelete