Monday 1 June 2020

Build and Push Docker Images with Jenkins

In this guide we'll see how to build a Docker image and push it to a Docker registry using a Declarative Pipeline in Jenkins.


Jenkins on Docker for .NET projects – Tech Blog by Alex Smagin

What you need:

In our post we'll use a simple "Hello World!" (written in Node.JS) application as an example.

Steps of the pipeline:
  1. Clone the source repository
  2. Build the application
  3. Build Docker image 
  4. Push image to Docker registry

Source code.

Our application source code is organized as follows:

simple-nodejs-app
├── Dockerfile
├── index.js
└── package.json

The content of the Dockerfile is the following:


FROM node:alpine
ADD . /
USER node
EXPOSE 3000
CMD npm run start

We want to build an image called mynode:latest and push it to https://myregistry.


Credentials.

Create a credentials resource on Jenkins, to access the Docker registry:


In this example, we've named the credentials resource registrycredentials


How to build and push a Docker Image with Jenkins?

This table summarizes how to translate Docker commands in Jenkins pipeline instructions:


Docker command         Equivalent in Jenkins pipeline 

docker build myregistry/mynode:latest
 
docker.build("myregistry/mynode:latest")
docker push myregistry/mynode:latest
withDockerRegistry(
    credentialsId: 'registrycredentials',
    url: "https://myregistry") {
        docker_image.push("latest")
}



Complete source code of the pipeline.

Now that we have all the resources, let's see the complete pipeline:


pipeline { agent any stages { stage('Clone sources') { steps { git credentialsId: 'mygitcredentials', branch: 'develop', url: 'https://git.mycompany.com/simple-node-js-app.git' } } stage('Install npm packages') { steps { nodejs(nodeJSInstallationName: 'node13') { sh 'npm i' sh 'npm rebuild node-sass' } } } stage('Build app') { steps { nodejs(nodeJSInstallationName: 'node13') { sh 'npm run build:dev' } } } stage("Build Docker image") { steps { script { docker_image = docker.build("myregistry/mynode:latest") } } } stage("Push images") { steps { script { withDockerRegistry(credentialsId: 'registrycredentials', url: "https://myregistry") {
docker_image.push("latest") } } } }

If you want to learn more about Docker and Jenkins, visit our CICD and DevOps pages!





No comments:

Post a Comment