pkg打包项目

https://github.com/vercel/pkg#readme

项目使用 dotenv加载.env配置

require('dotenv').config()
PORT=3000
# jwt secret
JWT_SECRET=ABCDabcd1234567890

package.json中声明pkg的打包配置

"bin": "server.js", // 入口文件
"pkg": {
  "targets": [
    "node18-linux-x64" // 打包平台
  ],
  "outputPath": "lib" // 输出目录
},

执行pkg .打包

首次打包会先下载平台对应的node二进制文件很慢

手动下载地址 https://github.com/vercel/pkg-fetch/releases

下载后放到pkg的缓存目录

pkg@5.8.1对应的目录是 ~/.pkg-cache/v3.4修改文件名 fetched-xxx-xxx

使用pm2启动项目

pkg打包后需要指定环境配置

pm2 start express-admin --env production

或者使用配置文件方式:pm2 start ecosystem.config.js --env production

module.exports = {
  apps: [
    {
      name: 'express-admin',
      script: './lib/express-admin',
      env_production: {
        NODE_ENV: "production",
        PORT: 3000,
      }
    }
  ]
};

使用Github Actions Workflows自动打包上传服务器

在 Github>Settings>secrets and variables>Actions>new repository secrets 新建密钥SSH_PRIVATE_KEY,环境变量REMOTE_HOST等,

打包完成后

easingthemes/ssh-deploy上传文件到服务器

appleboy/ssh-action登录服务器需要SSH_PRIVATE_KEY,重启应用 pm2 restart express-admin

http://blog.peijunlei.top/archives/1753499222910

完整配置如下

# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs

name: Node.js CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [18.x]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
    - uses: actions/checkout@v4
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'yarn'
    - name: Install and Build 😍
      run: |
          yarn
          yarn pkg
    - name: upload lib to ecs 💖
      uses:  easingthemes/ssh-deploy@v5.0.0
      with:
          SSH_PRIVATE_KEY: ${{secrets.SSH_PRIVATE_KEY}}
          REMOTE_HOST: ${{secrets.REMOTE_HOST}}
          REMOTE_USER: root
          SOURCE: lib # 打包后的目录
          TARGET: /root/data/express-admin # 上传到服务器的目录
    - name: ssh login & restart
      uses: appleboy/ssh-action@v1.0.3
      with:
          host: ${{secrets.REMOTE_HOST}}
          username: root
          key: ${{secrets.SSH_PRIVATE_KEY}}
          script: |
              export NVM_DIR=~/.nvm
              source ~/.nvm/nvm.sh  
              pm2 ls
              pm2 restart express-admin
              pm2 save
      

报错:err: bash: pm2: command not found

解决:增加脚本

export NVM_DIR=~/.nvm

source ~/.nvm/nvm.sh