2023.01 最新內容已更新於 BLOG
Eric: 接著,我們單獨討論 Jenkins 與 Docker 的串接方式
吉米: OK。

如果曾經使用 Jenkins 進行發佈,或許對 pipeline 並不陌生。
在 Pipeline 中,Jenkins 會依據 jenkinsfile 內容的指示執行各種動作。運用 Groovy 的格式來撰寫 jenkinsfile 讓使用者可以客制化建置的流程與環境。
經由 jenkinsfile 與 docker 的配合,我們可以自行訂定各 階段 (stages) ,使用不同 Docker Image 建置環境,執行不同的動作。而無需手動配置環境。
下面的範例,在 測試階段,調用 node,js 的 docker image 做為執行環境,然後執行 node.js 的相關動作。
Jenkinsfile (Declarative Pipeline)
pipeline {
agent {
docker { image 'node:7-alpine' }
}
stages {
stage('Test') {
steps {
sh 'node --version'
}
}
}
}
Pipeline 支援運用 dockerfile,進行 docker image 的建立與執行。
當我們將 jenkinsfile 中,使用 agent { dockerfile true } ,Pipeline 就會使用 Repository 根目錄下的 dockerfile ,進行 docker image 的建立與執行。
pipeline {
agent { dockerfile true }
stages {
stage('Test') {
steps {
sh 'node --version'
sh 'svn --version'
}
}
}
}
此外,也可以在 agent 內直接下 docker 指令。
agent {
docker {
image 'myregistry.com/node'
label 'my-defined-label'
registryUrl 'https://myregistry.com/'
registryCredentialsId 'myPredefinedCredentialsInJenkins'
}
}
或是在 agent 內寫 dockerfile 的內容。
agent {
// Equivalent to "docker build -f Dockerfile.build --build-arg version=1.0.2 ./build/
dockerfile {
filename 'Dockerfile.build'
dir 'build'
label 'my-defined-label'
additionalBuildArgs '--build-arg version=1.0.2'
args '-v /tmp:/tmp'
}
}
關於 Pipeline 中,agent 部份的其他語法,如果有興趣,可以參考官方文件。
雖然 Jenkins 的官方文件中,沒有特別說明到 docker-compose 的部份。但筆者很幸運找到 Symfony 在 Jenkins 運用 docker-compose 的文章 ( A continuous integration pipeline with Jenkins in Docker )。
下面,筆者擷取部份 jenkinsfile 的內文。
pipeline {
agent { label 'docker' }
triggers {
bitbucketPush()
}
environment {
// Specify your environment variables.
APP_VERSION = '1'
}
stages {
stage('Build') {
steps {
// Print all the environment variables.
sh 'printenv'
sh 'echo $GIT_BRANCH'
sh 'echo $GIT_COMMIT'
echo 'Install non-dev composer packages and test a symfony cache clear'
sh 'docker-compose -f build.yml up --exit-code-from fpm_build --remove-orphans fpm_build'
echo 'Building the docker images with the current git commit'
sh 'docker build -f Dockerfile-php-production -t registry.example.com/symfony_project_fpm:$GIT_COMMIT .'
sh 'docker build -f Dockerfile-nginx -t registry.example.com/symfony_project_nginx:$GIT_COMMIT .'
sh 'docker build -f Dockerfile-db -t registry.example.com/symfony_project_db:$GIT_COMMIT .'
}
}
}
}
從範例中,可以看到 docker-compose 的使用點,是 位於 steps 內,以 命令列 的方式執行。不像 dockerfile ,Jenkins 有直接的支援。
筆者將其再次精減,可以很清楚的看到 docker-compose 的使用方式。
pipeline {
agent { label 'docker' }
stages {
steps {
sh 'docker-compose -f build.yml up --exit-code-from fpm_build --remove-orphans fpm_build'
}
}
}
最後,該篇文章也分享它們執行 jenkinsfile 的畫面。
從圖中,真的可以發現 Symfony 活用 Jenkins Pipeline 功能,建立起 建置、測試、發佈 一連串自動化 CI/CD 流程。

(圖片來源: A continuous integration pipeline with Jenkins in Docker)
吉米: 哇,每個 CI Server 的設定方式,設定的方式都不太相同。
Eric: 是啊。不過,再怎麼變化,都是離不開 docker 的指令、 dockerfile、docker-compose.yml 這三個部份。
吉米: 嗯嗯,還要多試幾次,才能把 docker 摸的比較了解。
Eric: 一起加油吧。
<< 完 >>