第一个流水线 #

一、准备工作 #

1. 创建GitLab项目 #

首先需要在GitLab上创建一个项目:

  1. 登录GitLab(可以使用GitLab.com或私有实例)
  2. 点击"New Project"创建新项目
  3. 选择"Create blank project"
  4. 填写项目名称,如"my-first-pipeline"
  5. 点击"Create project"

2. 克隆项目到本地 #

bash
git clone https://gitlab.com/your-username/my-first-pipeline.git
cd my-first-pipeline

3. 创建示例文件 #

创建一个简单的Node.js项目作为示例:

bash
# 初始化项目
npm init -y

# 创建源文件
mkdir -p src
cat > src/index.js << 'EOF'
function hello(name) {
  return `Hello, ${name}!`;
}

module.exports = { hello };
EOF

# 创建测试文件
mkdir -p test
cat > test/index.test.js << 'EOF'
const { hello } = require('../src/index');

test('hello function', () => {
  expect(hello('World')).toBe('Hello, World!');
});
EOF

# 安装测试框架
npm install --save-dev jest

更新package.json:

json
{
  "name": "my-first-pipeline",
  "version": "1.0.0",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest": "^29.0.0"
  }
}

二、创建.gitlab-ci.yml #

1. 最简单的Pipeline #

创建.gitlab-ci.yml文件:

yaml
stages:
  - test

test_job:
  stage: test
  image: node:18
  script:
    - npm install
    - npm test

2. 提交并推送 #

bash
git add .
git commit -m "Add first pipeline"
git push origin main

3. 查看Pipeline #

  1. 打开GitLab项目页面
  2. 点击左侧菜单"Build" → “Pipelines”
  3. 可以看到正在运行的Pipeline
  4. 点击Pipeline查看详细状态

三、Pipeline状态 #

状态类型 #

状态 说明
pending 等待执行
running 正在执行
success 执行成功
failed 执行失败
canceled 已取消
skipped 已跳过

查看Job日志 #

点击具体的Job可以查看详细日志:

text
Running with gitlab-runner 15.0.0
  on runner-xxx
Preparing the "docker" executor
Pulling docker image node:18 ...
Running on runner-xxx via docker...
$ npm install
added 123 packages in 5s
$ npm test
PASS test/index.test.js
  ✓ hello function (5 ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Job succeeded

四、添加更多Stage #

完整的CI/CD Pipeline #

yaml
stages:
  - build
  - test
  - deploy

build_job:
  stage: build
  image: node:18
  script:
    - echo "Building the application..."
    - npm install
    - npm run build || echo "No build script"
  artifacts:
    paths:
      - node_modules/

test_job:
  stage: test
  image: node:18
  script:
    - echo "Running tests..."
    - npm test
  dependencies:
    - build_job

deploy_job:
  stage: deploy
  image: alpine:latest
  script:
    - echo "Deploying to production..."
    - echo "This is a simulated deployment"
  only:
    - main
  when: manual

Pipeline可视化 #

text
┌─────────────────────────────────────────────────────────┐
│                      Pipeline                            │
├─────────────────────────────────────────────────────────┤
│  ┌─────────┐   ┌─────────┐   ┌─────────┐               │
│  │  Build  │ → │  Test   │ → │ Deploy  │               │
│  │   ✓     │   │   ✓     │   │ (手动)  │               │
│  └─────────┘   └─────────┘   └─────────┘               │
└─────────────────────────────────────────────────────────┘

五、常用配置项 #

1. 指定镜像 #

yaml
job_name:
  image: node:18
  script:
    - npm test

2. 指定服务 #

yaml
test_with_db:
  image: node:18
  services:
    - postgres:14
  variables:
    POSTGRES_DB: test
    POSTGRES_USER: test
    POSTGRES_PASSWORD: test
  script:
    - npm test

3. 设置变量 #

yaml
variables:
  NODE_ENV: "test"
  DATABASE_URL: "postgres://test:test@postgres:5432/test"

test_job:
  script:
    - echo $NODE_ENV
    - npm test

4. 缓存依赖 #

yaml
cache:
  paths:
    - node_modules/

test_job:
  script:
    - npm install
    - npm test

5. 保存产物 #

yaml
build_job:
  script:
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 week

六、触发条件 #

1. 分支触发 #

yaml
deploy_job:
  script:
    - echo "Deploying..."
  only:
    - main
    - develop

2. 标签触发 #

yaml
release_job:
  script:
    - echo "Creating release..."
  only:
    - tags

3. 手动触发 #

yaml
deploy_production:
  script:
    - echo "Deploying to production..."
  when: manual

4. 条件触发 #

yaml
deploy_job:
  script:
    - echo "Deploying..."
  only:
    variables:
      - $CI_COMMIT_BRANCH == "main"

七、失败处理 #

1. 允许失败 #

yaml
lint_job:
  script:
    - npm run lint
  allow_failure: true

2. 重试 #

yaml
flaky_test:
  script:
    - npm test
  retry:
    max: 2
    when:
      - script_failure

3. 超时设置 #

yaml
long_running_job:
  script:
    - ./long-script.sh
  timeout: 3h

八、实战练习 #

练习1:多环境部署 #

yaml
stages:
  - test
  - deploy

test:
  stage: test
  image: node:18
  script:
    - npm install
    - npm test

deploy_staging:
  stage: deploy
  image: alpine:latest
  script:
    - echo "Deploying to staging..."
  environment:
    name: staging
    url: https://staging.example.com
  only:
    - develop

deploy_production:
  stage: deploy
  image: alpine:latest
  script:
    - echo "Deploying to production..."
  environment:
    name: production
    url: https://example.com
  only:
    - main
  when: manual

练习2:并行测试 #

yaml
stages:
  - test

test_unit:
  stage: test
  image: node:18
  script:
    - npm install
    - npm run test:unit

test_integration:
  stage: test
  image: node:18
  script:
    - npm install
    - npm run test:integration

test_e2e:
  stage: test
  image: node:18
  script:
    - npm install
    - npm run test:e2e

练习3:代码质量检查 #

yaml
stages:
  - quality

lint:
  stage: quality
  image: node:18
  script:
    - npm install
    - npm run lint
  allow_failure: true

audit:
  stage: quality
  image: node:18
  script:
    - npm audit
  allow_failure: true

九、常见问题 #

1. Pipeline没有触发 #

检查以下几点:

  • .gitlab-ci.yml文件是否在项目根目录
  • 文件名是否正确(注意前面的点)
  • YAML语法是否正确
  • Runner是否可用

2. Job一直pending #

可能原因:

  • 没有可用的Runner
  • Runner标签不匹配
  • Runner正在执行其他Job

3. Job执行失败 #

查看Job日志,常见原因:

  • 镜像不存在
  • 脚本命令错误
  • 依赖安装失败
  • 测试未通过

十、调试技巧 #

1. 使用echo调试 #

yaml
debug_job:
  script:
    - echo "Current directory: $(pwd)"
    - echo "Files: $(ls -la)"
    - echo "Environment: $ENV_VAR"

2. 使用before_script #

yaml
before_script:
  - echo "Starting job..."
  - whoami
  - pwd

job_name:
  script:
    - echo "Running main script..."

3. 交互式调试 #

yaml
debug_job:
  script:
    - sleep 3600
  when: manual
  timeout: 1h

然后使用GitLab的Web Terminal进行调试。

下一步 #

现在你已经创建了第一个流水线,接下来让我们深入了解 .gitlab-ci.yml详解

最后更新:2026-03-28