示例一 通用 Node.js 流水线(含产物与缓存)
stages:
- build
- test
- deploy
variables:
NODE_VERSION: "18"
cache:
paths:
- node_modules/
build_job:
stage: build
image: node:$NODE_VERSION
script:
- npm ci
- npm run build --if-present
artifacts:
paths:
- build/
expire_in: 1 week
test_job:
stage: test
image: node:$NODE_VERSION
script:
- npm test -- --ci
dependencies:
- build_job
deploy_staging:
stage: deploy
image: alpine:latest
script:
- echo "Deploying to staging..."
# 例如 rsync/ssh 部署到你的服务器
environment:
name: staging
url: https://staging.example.com
only:
- main
要点:用 cache 复用 node_modules,用 artifacts 将 build/ 传递给测试与部署;通过 environment 标记环境,用 only 限定分支触发。
示例二 Docker 镜像构建与部署(推送到 GitLab 容器镜像库)
stages:
- build
- test
- deploy
variables:
DOCKER_DRIVER: overlay2
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
build_job:
stage: build
image: docker:24
services:
- docker:24-dind
script:
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
only:
- merge_requests
- main
test_job:
stage: test
image: docker:24
services:
- docker:24-dind
script:
- docker run --rm $IMAGE_TAG npm test -- --ci
only:
- merge_requests
- main
deploy_prod:
stage: deploy
image: alpine:latest
script:
- echo "Deploying $IMAGE_TAG to production..."
# 例如 docker-compose pull && docker-compose up -d
environment:
name: production
url: https://prod.example.com
only:
- main
要点:使用 docker:dind 作为服务容器进行镜像构建与运行;通过 CI_REGISTRY_IMAGE/CI_COMMIT_REF_SLUG 等内置变量规范镜像标签;在 only 中区分 merge_requests(用于预览与质量门禁)与 main(用于生产发布)。