我刚刚进入了CI/CD的(美妙的(世界并拥有工作管道。但是,它们不是最佳的。
该应用程序是一个码头工人化的网站:
- 源代码需要由
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
。这不是必需的,并且会减慢部署速度。有没有办法说明需要为特定作业添加这样那样的包(而不是全局添加到所有作业中(?
要明确一点:这不是一个表演障碍(实际上根本不可能是一个问题(,但我担心我对这种工作自动化的方法是不正确的。
您不一定需要对所有作业使用相同的图像。让我向您展示我们的一个管道(部分(它做了类似的事情,只是使用 php 的 composer
而不是 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 镜像中用作构建器镜像。