What you need:
- A Jenkins instance
- Docker Plugin: https://plugins.jenkins.io/docker-workflow
- A code repository with a Dockerfile
In our post we'll use a simple "Hello World!" (written in Node.JS) application as an example.
Steps of the pipeline:
- Clone the source repository
- Build the application
- Build Docker image
- Push image to Docker registry
Source code.
Our application source code is organized as follows:
simple-nodejs-app
├── Dockerfile
├── index.js
└── package.json
├── 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
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")
}
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")
}
}
}
}
No comments:
Post a Comment