GitLab CI 卡在正在运行的 NodeJS 服务器上

Man*_*dFR 4 node.js gitlab gitlab-ci

我正在尝试使用 GitLab CI 在服务器上构建、测试和部署 Express 应用程序(运行器与 shell 执行器一起运行)。但是,test:asyncdeploy_staging作业不会终止。但是当检查 GitLab 内的终端时,Express 服务器确实启动了。是什么赋予了 ?

stages:
  - build
  - test
  - deploy

### Jobs ###

build:
  stage: build
  script:
    - npm install -q
    - npm run build
    - knex migrate:latest
    - knex seed:run
  artifacts:
    paths:
      - build/
      - node_modules/
  tags:
    - database
    - build

test:lint:
  stage: test
  script:
    - npm run lint
  tags:
    - lint

# Run the Express server
test:async:
  stage: test
  script:
   - npm start &
   - curl http://localhost:3000
  tags:
   - server

deploy_staging:
  stage: deploy
  script:
    - npm start
  environment:
    name: staging
    url: my_url_here
  tags:
    - deployment
Run Code Online (Sandbox Code Playgroud)

npm start只是node build/bundle.js。构建脚本使用 Webpack。

小智 5

注意:当使用 gitlab runner 时,解决方案工作正常shell executor

一般来说,在 Gitlab CI 中,我们运行具有特定任务的有序作业,这些任务应该在另一个任务结束后执行。

因此,对于作业,build我们有一个npm install -q运行并以退出状态终止的命令(如果命令成功,则为 0 退出状态),然后运行下一个命令,npm run build依此类推,直到作业终止。

对于该test作业,我们有npm start &一个持续运行的进程,因此该作业将无法终止。

问题是,有时我们需要一些进程需要在后台运行,或者一些进程在任务之间保持活动状态。例如,在某种测试中,我们需要保持服务器运行,如下所示:

test:
  stage: test
  script:
   - npm start
   - npm test
Run Code Online (Sandbox Code Playgroud)

在这种情况下npm test永远不会启动,因为npm statrt它会继续运行而不终止。

解决方案是使用before_script我们运行的 shell 脚本来保持npm start进程运行,然后调用after_script杀死该npm start进程

所以我们在.gitlab-ci.yml上写

test:
  stage: test
  before_script:
    - ./serverstart.sh
  script:
   - npm test
  after_script:
    - kill -9 $(ps aux | grep '\snode\s' | awk '{print $2}')
Run Code Online (Sandbox Code Playgroud)

并在serverstart.sh上

test:
  stage: test
  script:
   - npm start
   - npm test
Run Code Online (Sandbox Code Playgroud)

感谢该serverstart.sh脚本在保持进程处于活动状态的同时终止npm start,并帮助我们转移到我们现有的工作npm test

npm test终止并传递到 after 脚本,我们在其中杀死所有 Nodejs 进程。