GitLab CI坚持运行NodeJS服务器

时间:2018-02-27 16:44:27

标签: node.js gitlab gitlab-ci

我正在尝试使用GitLab CI在服务器上构建,测试和部署Express应用程序(Runner正在使用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

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

2 个答案:

答案 0 :(得分:0)

您在测试阶段开始后台作业永远不会终止 - 因此作业将永远运行。

GitLab CI作业的想法是短期运行的任务 - 比如编译,执行单元测试或收集代码覆盖率等信息 - 这些任务以预定义的顺序执行。在您的情况下,订单是build -> test -> deploy;由于test工作尚未完成,deploy甚至无法执行。

根据您的环境,您必须为部署节点应用创建不同的作业。例如,您可以使用scp之类的工具将构建输出推送到远程服务器,或将其上传到AWS;之后,您可以在url:中的.gitlab-ci.yml字段中引用最终到达网址。

答案 1 :(得分:0)

注意:当将gitlab运行程序与shell executor

一起使用时,解决方案可以正常工作

通常,在Gitlab CI中,我们运行带有特定任务的有序作业,这些任务应在另一任务结束后执行。

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

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

问题在于,有时我们需要一些需要在后台运行的流程,或者需要一些在任务之间不停运行的流程。例如,在某种测试中,我们需要保持服务器运行,诸如此类:

test:
  stage: test
  script:
   - npm start
   - npm test

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

解决方案是使用before_script,在其中运行使npm start进程保持运行的Shell脚本,然后调用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}')

并在 serverstart.sh

# !/bin/bash

# start the server and send the console and error logs on nodeserver.log
npm start > nodeserver.log 2>&1 &

# keep waiting until the server is started 
# (in this case wait for mongodb://localhost:27017/app-test to be logged)
while ! grep -q "mongodb://localhost:27017/app-test" nodeserver.log
do
  sleep .1
done
echo -e "server has started\n"
exit 0

由于该serverstart.sh脚本已终止,同时使npm start进程保持活动状态,并通过转移到我们拥有npm test的工作来帮助我们。

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

相关问题