npm install
命令后会在项目中生成 ./node_modules
,缓存储存在 ~/.npm
目录,后者体积更小,更通用。包管理工具 | 缓存目录 |
Maven | /root/.m2/ |
Gradle | /root/.gradle/ |
npm | /root/.npm/ |
composer | /root/.cache/composer/ |
pip3 | /root/.cache/pip/ |
yarn | /usr/local/share/.cache/yarn/ |
pipeline {agent anystages {stage('检出') {steps {checkout([$class: 'GitSCM',branches: [[name: env.GIT_BUILD_REF]],userRemoteConfigs: [[url: env.GIT_REPO_URL, credentialsId: env.CREDENTIALS_ID]]])}}stage('Java 缓存') {agent {docker {image 'adoptopenjdk:11-jdk-hotspot'args '-v /root/.gradle/:/root/.gradle/ -v /root/.m2/:/root/.m2/'reuseNode true}}steps {sh './gradlew test'}}stage('npm 缓存') {steps {script {docker.image('node:14').inside('-v /root/.npm/:/root/.npm/') {sh 'npm install'}}}}}}
/home/ubuntu/.npm/
,那么对应的代码为:docker.image('node:14').inside('-v /home/ubuntu/.npm/:/root/.npm/') {sh 'npm install'}
Dockerfile
基础镜像、 CI agent 镜像,那么通常会耗费大量时间,此时就可以通过缓存进行加速。Jenkinsfile
,修改镜像名称即可复用:pipeline {agent anyenvironment{DOCKER_CACHE_EXISTS = fileExists '/root/.cache/docker/php-8.0-cli.tar'}stages {stage('加载缓存') {when { expression { DOCKER_CACHE_EXISTS == 'true' } }steps {sh 'docker load -i /root/.cache/docker/php-8.0-cli.tar'}}stage('使用镜像(请修改此段)') {agent {docker {image 'php:8.0-cli'args '-v /root/.cache/:/root/.cache/'reuseNode 'true'}}steps {sh "php -v"}}stage('生成缓存(仅运行一次)') {when { expression { DOCKER_CACHE_EXISTS == 'false' } }steps {sh 'mkdir -p /root/.cache/docker/'sh 'docker save -o /root/.cache/docker/php-8.0-cli.tar php:8.0-cli'}}}}
/root/.cache/
路径,此时第二次的构建耗时明显更短,说明缓存已生效:⚠️ 缓存镜像会逐渐过时,建议定时清除,与官方更新保持一致。
Dockerfile
作为构建环境,需要运行 docker build
命令用以初始化,较为不便。可以将已构建的 Docker 镜像保存到仓库,方便二次拉取复用。// 创建 CODING Docker 制品库,获取用户名、密码和仓库地址sh "docker login -u $DOCKER_USER -p $DOCKER_PASSWORD my-team-docker.pkg.coding.net"// 使用 Dockerfile 的 md5 做 tagmd5 = sh(script: "md5sum Dockerfile | awk '{print \\$1}'", returnStdout: true).trim()imageFullName = "my-team-docker.pkg.coding.net/my-project/my-repo/my-app:dev-${md5}"// 检查镜像是否已存在远端仓库dockerNotExists = sh(script: "docker manifest inspect $imageFullName > /dev/null", returnStatus: true)def testImage = nullif (dockerNotExists) {testImage = docker.build("$imageFullName", "--build-arg APP_ENV=testing ./")sh "docker push $imageFullName"} else {testImage = docker.image(imageFullName)}// 使用镜像进行自动化测试testImage.inside("-e 'APP_ENV=testing'") {stage('test') {echo 'testing...'sh 'ls'echo 'test done.'}}
$ docker manifest inspect ecoding/foo:barno such manifest$ echo $?1
本页内容是否解决了您的问题?