Before reading this blog, check out the first part of the series.
In this part, we’ll integrate a private GitHub repository with Jenkins by adding credentials and automate the process of building and pushing Docker images.
Access Jenkins GUI:
Add Credentials:
github-creds
.You should now see the credentials listed.
We’ll create a Jenkins pipeline to check out the source code from GitHub.
Create a New Pipeline:
Define the Pipeline Script:
Use the following script to check out the code:
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git(branch: 'master', credentialsId: 'github-creds', url: 'https://github.com/github_user/private-repository.git')
}
}
}
}
Replace github_user/private-repository.git
with your repository’s URL.
We’ll use a basic Maven Spring Boot web application project. You can create one at start.spring.io, selecting version 2.4.1 and Java 8.
Create a Dockerfile
in your project with the following content:
FROM openjdk:8-jdk-alpine
COPY . /data
WORKDIR /data
RUN ["mvn", "clean", "install"]
COPY target/*.jar ./app.jar
ENTRYPOINT ["java", "-Xmx750m", "-jar", "app.jar"]
Create a DockerHub Account:
Add DockerHub Credentials to Jenkins:
dockerhub-creds
.We’ll use Jenkins plugins to interact with Docker:
Install Required Plugins:
Install them via Manage Jenkins > Manage Plugins > Available tab.
Define Build and Push Stages:
Update your Jenkinsfile
with the following stages:
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git(branch: 'master', credentialsId: 'github-creds', url: 'https://github.com/github_user/private-repository.git')
}
}
stage('Build') {
steps {
script {
newImage = docker.build 'yourdockerhubuser/javaapp'
}
}
}
stage('Push') {
steps {
script {
docker.withRegistry('', 'dockerhub-creds') {
newImage.push("${env.BUILD_NUMBER}")
}
}
}
}
}
}
Replace yourdockerhubuser
with your DockerHub username.
Build Stage:
yourdockerhubuser/javaapp
.Push Stage:
In the next episode, we will continue by preparing a deployment Ansible playbook, triggering the playbook within Jenkins, and setting up the monitoring baseline.
Stay tuned!