[教程] 如何提速 AWS Codebuild (从每次 30~40分钟优化到5分钟以下)
AWS 中国区(北京)
![[教程] 如何提速 AWS Codebuild (从每次 30~40分钟优化到5分钟以下)](/content/images/size/w2000/2020/02/codebuild2.jpg)
这篇文章讲什么
如何优化 AWS 中国区的 CodeBuild 速度
这篇文章对谁有用
使用 AWS Codebuild 的程序员
有什么用
看怎么提速
先讲结论(TLDR; 太长不看)
最有效的解决办法是:https://github.com/aws/aws-codebuild-docker-images/issues/26#issuecomment-370177343

我是这样写的:

核心点:
- 这个 buildspec.yml 是指令 Codebuild 怎么进行 Build 的配置文件
- 在 pre_build 里面 docker pull
- 在 build 里面 docker build --cache-from
这就可以了
结论说完了,如果想关掉文章可以关了。如果你关心细节可以继续往下看
前言
我最近(2020年2月)在远程工作,给一家北京的公司干活。
公司产品用到了 AWS 中国区的各种工具,比如 ECS, ECR, Codebuild 等等。
整体部署流程是:
- 触发 Codebuild, Codebuild 会去 Github 把代码拿到,最后 build 出一个 Docker Image
- 把这个 Docker image 推到 AWS ECR
- 触发 AWS ECS, 从而达到线上更新的效果
额外信息
之前的工程师是美国人,
2019年6月开始做这个项目。
2020年2月我们中国工程师接手项目。
部署的时候发现了问题


总结两点:
- "失败"和"已停止"挺多的
- 哪怕"成功",时间范围也非常大,短的有7分50秒,最长的有1小时19分钟。
问题在哪里?
部署太久了,需要提速。最好是每次5分钟以下。
解决办法1:启用 AWS Codebuild 自带的缓存(没用)
(截止至2020年2月17号)
如果你去网上搜怎么提速,
会看到这篇文章:

打开是这样的:

然后它会告诉你启用缓存:

如果用中文版的 AWS。
这里找:


实测结果是:用处不大
如果两次 build 间隔很短,只有几分钟,那么这个缓存就会生效。
具体这个缓存会存在多久,官方没有给出具体参数。

27分钟29秒这个。结束时间是2020-2-13 4:19

1分3秒这个。开始时间是2020-2-13 4:21

27分钟29秒和1分30秒的这两次 Build。间隔才 3 分钟。
我们再来看看之后的 Build:

34分钟14秒这个。开始时间是 2020-2-13 7:20。晚上7点。

可以得出:
间隔3分钟,缓存有效。
间隔3小时,缓存没了。
结论:
这方法没什么用,我们每次部署都是间隔好几天的。
因为肯定是本地开发完了才部署线上测试环境嘛。
有效的解决办法
在文章一开头就说了。我也就不重复了。
这里提供下 buildspec.yml
方便复制粘贴
https://gist.github.com/1c7/b0b0c0e25521da8adf5d068fc210a3bd
证明有效

最近3次 Build 都在5分钟以下了,
而且还隔了2天。说明这个方法是有效的。