持续集成中的代码构建耗时主要集中在两个部分:获取依赖和代码编译。使用Flow的自定义缓存可以有效降低获取依赖的耗时。本文介绍如何加速常见编译工具的构建效率。
Yarn 构建加速
使用中国内地 registry 和 mirror
使用中国内地 registry 仓库避免由于海外网络访问导致的依赖下载缓慢的问题。
yarn config set registry https://registry.npmmirror.com
对于构建中由于 Building fresh packages 导致构建慢的情况需要指定特定外部依赖的中国内地镜像源:
yarn config set sass_binary_site "https://npmmirror.com/mirrors/node-sass/"
除了通过 yarn config set 指定依赖下载路径以外,还可以通过.yarnrc进行配置。在项目根路径中创建.yarn并配置以下内容:
registry "https://registry.npmmirror.com"
sass_binary_site "https://npmmirror.com/mirrors/node-sass/"
phantomjs_cdnurl "https://cdn.npmmirror.com/binaries/phantomjs"
electron_mirror "https://cdn.npmmirror.com/binaries/electron/"
sqlite3_binary_host_mirror "https://foxgis.oss-cn-shanghai.aliyuncs.com/"
chromedriver_cdnurl "https://cdn.npmmirror.com/binaries/chromedriver"
配置yarn全局缓存
设置缓存目录,并在流水线自定义缓存中添加缓存目录 /root/.yarn
配置。
# 设置全局缓存
yarn config set cache-folder ~/.yarn
# 构建中优先使用缓存中
yarn install --prefer-offline
通过以上命令设置缓存目录,并确保下载依赖过程中优先使用本地缓存,减少外部网络依赖下载的时间。
Npm构建加速
使用中国内地 registry 和 mirror
或者直接使用 cnpm。
对于使用 npm 的用户可以创建.npmrc
并设置以下内容:
registry="https://registry.npmmirror.com"
sass_binary_site="https://npmmirror.com/mirrors/node-sass/"
phantomjs_cdnurl="https://cdn.npmmirror.com/binaries/phantomjs"
electron_mirror="https://cdn.npmmirror.com/binaries/electron/"
sqlite3_binary_host_mirror="https://foxgis.oss-cn-shanghai.aliyuncs.com/"
chromedriver_cdnurl="https://cdn.npmmirror.com/binaries/chromedriver"
构建中使用全局缓存
构建时,设置 npm 的全局缓存路径,并在流水线自定义缓存配置中添加/root/.npm
缓存路径,并使用以下命令安装依赖包,优先从本地缓存获取:
npm config set cache ~/.npm
npm install --prefer-offline --no-audit
Golang构建加速
使用 go proxy
使用 Goproxy 从中国内地下载外部依赖:
export GOPROXY=https://goproxy.cn
添加go mod缓存
持久化 Go Mod 缓存。Flow 中 Go 构建环境的默认缓存目录是/go/pkg/mod。您只需在流水线自定义缓存中添加该缓存路径即可。 在构建过程中将会优先使用/go/pkg/mod中的本地缓存,从而减少由于外部网络请求导致的构建慢的问题。
Python构建加速
使用pypi镜像
使用阿里云pypi镜像。
pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
添加pip依赖缓存
缓存pip本地依赖,流水线自定义缓存配置中添加缓存目录/root/.cache/pip,确保pip install时优先从版本缓存中获取依赖包。
镜像构建加速
如果你的Dockerfile中FROM了dockerhub的镜像或者其他海外镜像,比如:
FROM nginx:1.19.1
.....
由于跨境网络问题,这种Dockerfile的构建会不稳定或者比较慢,可以使用以下方式解决:将境外镜像pull到本地,然后push到阿里云镜像仓库(cr.console.aliyun.com)的中国内地region(比如北京、上海等),然后修改您的Dockerfile中的FROM。比如:
docker pull nginx:1.19.1
docker tag nginx:1.19.1 registry.cn-beijing.aliyuncs.com/yournamespace/nginx:1.19.1
docker push registry.cn-beijing.aliyuncs.com/yournamespace/nginx:1.19.1
请确保容器镜像服务的命名空间yournamespace。