[Nuxt]vue项目使用PM2部署

☁Emo 这个Nuxt项目为例。

部署环境为:Ubuntu20.04 Nginx(1.18) Nuxt(2.15) PM2(5.2) nodejs(16.14) npm(8.5)

在运行前确保代码没问题,可现在项目根目录运行 npm run dev 确保项目能启动。

首先安装pm2

npm install pm2 -g

执行完毕后 运行pm2 -v打印版本号确定安装完毕

接下来在项目根目录创建文件:

vi ecosystem.config.js

将以下内容写入到文件内:(Nuxt官方文档

module.exports = {
  apps: [
    {
      name: 'NuxtEmo',
      exec_mode: 'cluster',
      instances: 'max', // Or a number of instances
      script: './node_modules/nuxt/bin/nuxt.js',
      args: 'start'
    }
  ]
}

接下来在同目录下运行以下命令编译

npm run build

在执行以下命令运行

pm2 start

执行完毕后,项目则运行起来,可稍等10秒左右通过以下命令查看状态:

pm2 ls

将会打印以下内容:

对应你的项目名称后面的status为online时则项目正常启动完毕。

接下来配置Nginx通过反代理端口的方式暴露端口,如果你还没安装nginx可通过以下命令安装:

sudo apt-get install nginx

如果你已经安装,进入到Nginx的配置下,新建一个配置,配置内容如下:(官方文档

map $sent_http_content_type $expires {
    "text/html"                 epoch;
    "text/html; charset=utf-8"  epoch;
    default                     off;
}

server {
    listen          80;             # 端口
    server_name     emo.abigeater.com;    # 你的服务器域名

    gzip            on;
    gzip_types      text/plain application/xml text/css application/javascript;
    gzip_min_length 1000;

    location / {
        expires $expires;

        proxy_redirect                      off;
        proxy_set_header Host               $host;
        proxy_set_header X-Real-IP          $remote_addr;
        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
        proxy_read_timeout          1m;
        proxy_connect_timeout       1m;
        proxy_pass                          http://127.0.0.1:3000; # set the address of the Node.js instance here
    }
}

主要是修改你的服务器域名和如果你修改了本地的端口下则需要修改反代理的端口即可。

最后执行一下sudo nginx -t确定配置文件正确,再重启一下nginx即可生效。

sudo nginx -s reload

则前端部署完毕。

之后修改了前端代码则在前端项目根目录执行以下即可:

npm update
npm run build
pm2 restart pm2项目名

自动化部署实例 ---> Github推送代码后利用Actions部署到服务器