并行执行原理

GitLab CI/CD 中,同一个 stage 的多个 job 默认会并行执行(前提是有足够的 Runner)。

方法一:同一 Stage 多个 Job

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stages:
- build
- test

job1:
stage: build
script:
- echo "This is job1"

job2:
stage: build
script:
- echo "This is job2"

test1:
stage: test
script:
- echo "This is test1"

test2:
stage: test
script:
- echo "This is test2"
  • job1job2build 阶段并行执行
  • test1test2test 阶段并行执行

方法二:使用 parallel 关键字

将单个作业分成多个并行实例:

1
2
3
4
5
test:
stage: test
script:
- echo "This is a parallel test"
parallel: 3

这会启动 3 个并行的 test 作业实例。

Runner 并发配置

确保 GitLab Runner 支持并发执行。

在 Runner 配置文件中设置 concurrent 值:

1
concurrent = 10

如果并发数设置过低,作业会排队等待,无法真正并行。

注意事项

  • 并行执行需要足够的可用 Runner
  • Runner 的 concurrent 值决定了最大并发作业数
  • 不同 stage 之间是串行执行的
  • 使用 parallel 关键字可以水平扩展单个作业