Now that I have my container images ready, I can build my site and deploy it.
Let’s make a Jenkins pipeline to handle the deployment.
This will not be an in depth description of how Jenkins works. I would suggest you look up a video on YouTube, Udemy or another online source if you’d like more information on that front.
Create pipeline
I’ll start by creating a new item in Jenkins and choose the “Pipeline” type and give it a memorable name.
Configure parameters
I choose to create a parameter for the container name.
Configure pipeline
For the pipeline section itself I chose to go with a jenkinsfile stored in the project rather than defining everything in the Jenkins web interface.
I also need to recursively pull the sub modules.
I haven’t setup an automatic trigger nor a set schedule. I feel it’s OK to just run the pipeline manually from the web interface as I don’t make that many changes to this blog.
Also I currently have the api token for my git repository just set in the url. I may move that at some point.
Jenkinsfile
Now let’s take a look at the jenkinsfile itself.
pipeline {
agent any
stages {
stage('Pull Container') {
steps {
echo 'Pull latest hugo-builder container image.'
sh 'docker pull my_container_repository/teknikuglen/hugo-builder:latest'
}
}
stage('Remove old output files') {
steps {
echo 'Cleanup old output files'
sh 'rm -Rf public/*'
}
}
stage('Build Site Files') {
steps {
echo 'Run container to build site files'
sh 'docker run --rm -v $(pwd):/src my_container_repository/teknikuglen/hugo-builder:latest hugo'
}
}
stage('Build Nginx Image') {
steps {
echo 'Build nginx container image'
sh 'docker build -t hugo-nginx:teknikuglen -f Containerfile .'
}
}
stage('Check Container Running') {
steps {
echo "Remove current container if it exists"
script {
def containerExists = sh (
script: "docker container inspect -f 'Container exists and is {{.State.Status}}' ${container_name} > /dev/null 2>&1",
returnStatus: true
) == 0
if (containerExists) {
sh "docker container stop ${container_name}"
sh "docker container rm ${container_name}"
} else {
echo "Container does not exist"
}
}
}
}
stage('Deploy New Container') {
steps {
echo "start new container"
sh 'docker run -d --restart unless-stopped --name ${container_name} --network my_container_bridge hugo-nginx:teknikuglen'
}
}
}
}
Mostly the commands are self explanatory. The one I had most trouble wrapping my head around is the part that checks if the container already exists.
Conclusion
And there you have it. A nice and easy way to deploy my web site. Naturally this only deploys the container. It says nothing about the proxy and TLS/Certificate I placed in front of it.
Maybe I’ll Cover that in a future post.