我刚刚进入CI / CD的(精彩)世界,并且有工作流程。但它们并不是最佳选择。
该应用程序是一个dockerized网站:
webpack
编译并最终在dist
dist
目录被复制到docker容器我目前的设置非常天真(我添加了一些评论来说明为什么我认为各种元素是必需/有用的):
# I start with a small image
image: alpine
# before the job I need to have npm and docker
# the problem: I need one in one job, and the second one in the other
# I do not need both on both jobs but do not see how to split them
before_script:
- apk add --update npm
- apk add docker
- npm install
- npm install webpack -g
stages:
- create_dist
- build_container
- stop_container
- deploy_container
# the dist directory is preserved for the other job which will make use of it
create_dist:
stage: create_dist
script: npm run build
artifacts:
paths:
- dist
# the following three jobs are remote and need to be daisy chained
build_container:
stage: build_container
script: docker -H tcp://eu13:51515 build -t widgets-sentinels .
stop_container:
stage: stop_container
script: docker -H tcp://eu13:51515 stop widgets-sentinels
allow_failure: true
deploy_container:
stage: deploy_container
script: docker -H tcp://eu13:51515 run --rm -p 8880:8888 --name widgets-sentinels -d widgets-sentinels
此设置工作位npm
和docker
安装在这两个作业中。这不是必需的,并且会降低部署速度。有没有办法说明需要为特定工作添加此类和此类包(而不是全局添加)?
为了说清楚:这不是一个显示阻止(实际上根本不可能是一个问题),但我担心我的这种工作自动化的方法是不正确的。
您不一定需要为所有作业使用相同的图像。让我告诉你我们的一个管道(部分)做类似的事情,只需用composer
for php而不是npm
:
cache:
paths:
- vendor/
build:composer:
image: registry.example.com/base-images/php-composer:latest # use our custom base image where only composer is installed on to build the dependencies)
stage: build dependencies
script:
- php composer.phar install --no-scripts
artifacts:
paths:
- vendor/
only:
changes:
- composer.{json,lock,phar} # build vendor folder only, when relevant files change, otherwise use cached folder form s3 bucket (configured in runner config)
build:api:
image: docker:18 # use docker image to build the actual application image
stage: build api
dependencies:
- build:composer # reference dependency dir
script:
- docker login -u gitlab-ci-token -p "$CI_BUILD_TOKEN" "$CI_REGISTRY"
- docker build -t $CI_REGISTRY_IMAGE:latest.
- docker push $CI_REGISTRY_IMAGE:latest
作曲家基础图像包含运行作曲家所需的所有包,因此在您的情况下,您将为npm
创建基本图像:
FROM alpine:latest
RUN apk add --update npm
然后,在create_dist
阶段使用此图像,并在其他阶段使用image: docker:latest
作为图像。
除了为不同的作业引用不同的图像,您还可以尝试gitlab锚点,为作业提供可重用的模板:
.install-npm-template: &npm-template
before_script:
- apk add --update npm
- npm install
- npm install webpack -g
.install-docker-template: &docker-template
before_script:
- apk add docker
create_dist:
<<: *npm-template
stage: create_dist
script: npm run build
...
deploy_container:
<<: *docker-template
stage: deploy_container
...
尝试多级构建器,可以中间临时映像并复制生成的内容最终的docker镜像。此外,npm应该是docker图像的一部分,创建一个npm图像并在最终的docker图像中用作构建器图像。