I was building inside a Maven container using Jenkins. Anyway, I wanted to create a Docker image all at once. It took longer than I expected.
src
Dockerfile
Jenkinsfile
pom.xml
I have the source and the above files in my git repository.
Dockerfile
FROM tomcat:jdk14-openjdk
COPY target/*.war /usr/local/tomcat/webapps/
The war file created by the build is stored under webapps. Manage in the same repository as your code.
Jenkinsfile
pipeline {
agent any
stages {
stage('delete_workspace') {
steps {
deleteDir()
}
}
stage('build') {
agent {
docker {
label 'master'
image 'maven:3.6.3-openjdk-14'
}
}
steps {
// Run Maven on a Unix agent.
sh "mvn clean package"
}
post {
success {
archiveArtifacts 'target/*.war'
}
}
}
stage('docker build') {
agent { label 'master'}
steps {
sh 'docker build -t test-tomcat:0.1 .'
}
////When deleting after the fact.
// post {
// always {
// deleteDir()
// }
// }
}
}
}
Created with Declarative Pipeline.
stage
pipeline {
agent any
stages {
If there is no agent any, the job failed, so it is described.
delete_workspace
stage('delete_workspace') {
steps {
deleteDir()
}
}
There is a pattern to delete the workspace in advance and always do it after the fact, but when an error occurs in the job, it is difficult to isolate personally if it is deleted, so it is a group to do it in advance of the job.
build
agent {
docker {
label 'master'
image 'maven:3.6.3-openjdk-14'
}
}
The maven container is running on the master node. It took me a while to realize that the node designation was in this position.
steps {
// Run Maven on a Unix agent.
sh "mvn clean package"
}
post {
success {
archiveArtifacts 'target/*.war'
}
}
I'm building maven and saving the artifacts.
docker build
stage('docker build') {
agent { label 'master'}
steps {
sh 'docker build -t test-tomcat:0.1 .'
}
////When deleting after the fact.
// post {
// always {
// deleteDir()
// }
// }
}
Since docker was started on the master, specify agent as the master. Since the artifacts built with the maven container and the Dockerfile are stored under the workspace of the host, Run docker build as it is.
I didn't know that the build result would remain in the host workspace even if I built without the container, so It took a long time to create. I also found that I had to write in Scripted Pipeline to do various things with docker in jenkins. As far as jenkins is concerned, it's simpler to call Ansible and docker-compose commands than to work hard with pipeline. I felt that maintainability was also high. Which one is it actually?
https://www.jenkins.io/doc/book/pipeline/docker/
Recommended Posts