使用 PM2 启动 herd 实践记录

痛点与目标

痛点

  • herd 服务无法在 erda 上进行热部署,无法在线上环境进行debug,修改代码验证问题
  • erda 上的日志无法筛选,且定位困难,有时会因为因为未知原因无法打开,甚至丢失日志

目标

  • herd 服务实现类似nginx reload的热部署实践
  • 利用 pm2 的日志功能实现 herd 日志过滤实践

实践

实践环境:招商采购商城项目开发环境

流水线修改

#
# 部署流水线配置
# 记得在流水线环境变量里面配置各env默认值
# PROJECT_TYPE           区分打包的应用 (b2c/b2b/sea/point 等)
# PROJECT_SUB_TYPE       区分打包的二级应用 (srm/brd等)
#
version: '1.1'
envs:
  PROJECT_NAME: gaia-mall

# pipeline 的不同阶段声明。
stages:
  - stage:
      - git-checkout:
          params:
            depth: 1

  - stage:
      - js-build:
          alias: pipeline-build
          version: '1.0'
          params:
            build_cmd:
              - npm ci
              # 开发时使用的 build 命令,二开项目需要在 redevelop 配置中替换为 npm run build
              - npm run build
            node_version: '14'
            workdir: ${git-checkout}
          resources:
            cpu: 2
            mem: 4096

  # 构建镜像
  - stage:
      - release:
          alias: release
          version: '1.0'
          params:
            dice_yml: ${pipeline-build}/dice.yml
            services:
              gaia-mall:
                cmd: sed -i "s^server_name .*^^g" /etc/nginx/conf.d/nginx.conf.template && envsubst "`printf '$%s' $(bash -c "compgen -e")`" < /etc/nginx/conf.d/nginx.conf.template > /etc/nginx/conf.d/default.conf && /usr/local/openresty/bin/openresty -g 'daemon off;'
                copys:
                  - ${pipeline-build}/public/:/app/
                  - ${pipeline-build}/nginx.conf.template:/etc/nginx/conf.d/
                image: registry.cn-hangzhou.aliyuncs.com/dice-third-party/terminus-nginx:0.2
              herd:
                cmd: cd /root/pipeline-build && echo 'Start gaia-mall service ...' && npm i pm2 -g && pm2 start npm --name srm-mall -- run 'server' && pm2 logs srm-mall
                copys:
                  - ${pipeline-build}:/root/
                image: registry.erda.cloud/erda-actions/terminus-debian-herd:1.1.11-n14.17
            workdir: ${pipeline-build}
          resources:
            cpu: 2
            mem: 2048

  # 部署
  - stage:
      - dice:
          params:
            time_out: 300
            release_id_path: ${release}

修改点:

  • 将 herd 服务的启动命令cmd,改为全局安装 pm2 并使用 pm2 运行服务的npm启动命令

pm2 start npm --name srm-mall -- run 'server' 此条命令可以让 pm2 运行npm scripts, run 后面输入npm script 的 key

启动效果

可以看到 herd 服务已经通过pm2正常启动,日志正常打印。 Alt text

进程管理

打开控制台输入进入服务目录运行pm2 status可查看当前管理的进程状态,可看到实际运行后,占用内存在40M左右 Alt text

日志管理

通过pm2 logs srm-mall 可查看最新日志,srm-mall 是指启动时指定的name Alt text

配合grep命令可以进行关键词过滤日志 Alt text

控制台调试代码

在控制台修改代码,health/check接口输出日志 Alt text 运行 pm2 restart srm-mall 重启服务 Alt text 重新输出日志,可以看到herd服务重新启动,修改的输入日志代码也生效了 Alt text

更多

更多 pm2 api可查看 https://pm2.keymetrics.io/docs/usage/quick-start/

results matching ""

    No results matching ""