You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PM2在指定端口启动Next.js应用?生产环境负载均衡配置

用PM2指定端口启动Next.js应用

方法1:命令行直接指定端口

Next.js通过PORT环境变量绑定端口,启动时直接在命令前注入环境变量即可:

# 启动名为next-app的应用,绑定3001端口
PORT=3001 pm2 start npm --name "next-app" -- run start

启动前需执行npm run build生成生产环境构建产物。

方法2:使用PM2配置文件(推荐生产环境)

创建ecosystem.config.js配置文件,集中管理应用参数:

module.exports = {
  apps: [
    {
      name: 'next-production',
      script: 'npm',
      args: 'run start',
      env: {
        NODE_ENV: 'production',
        PORT: 3001 // 自定义端口
      },
      instances: 'max', // 启用集群模式,占用所有CPU核心
      exec_mode: 'cluster',
      autorestart: true, // 进程崩溃自动重启
      watch: false // 生产环境关闭文件监听
    }
  ]
};

启动命令:

pm2 start ecosystem.config.js

验证启动状态:

pm2 list # 查看应用列表及端口
curl localhost:3001 # 测试端口是否可访问

生产环境故障转移与负载均衡配置(解决高负载与部署Bad Gateway)

1. PM2集群模式基础负载均衡

上述配置文件已启用cluster模式,PM2会自动将请求分发到多个实例,利用多核CPU提升性能,同时自带进程崩溃自动重启能力,实现基础故障转移。

2. Nginx反向代理与高级故障转移

配合Nginx做反向代理,实现更可靠的负载均衡、健康检查与故障转移,同时解决部署时的Bad Gateway问题。

Nginx配置示例

编辑Nginx配置文件(如/etc/nginx/nginx.conf或站点配置文件):

http {
  # 定义上游应用集群
  upstream next_cluster {
    server localhost:3001;
    server localhost:3002;
    server localhost:3003;
    # 故障转移规则:实例连续失败3次后,30秒内不再转发请求
    server localhost:3001 max_fails=3 fail_timeout=30s;
    server localhost:3002 max_fails=3 fail_timeout=30s;
    server localhost:3003 max_fails=3 fail_timeout=30s;
  }

  server {
    listen 80;
    server_name your-domain.com;

    location / {
      proxy_pass http://next_cluster;
      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;

      # 避免部署时Bad Gateway:设置代理超时与重试策略
      proxy_connect_timeout 30s;
      proxy_send_timeout 30s;
      proxy_read_timeout 30s;
      # 遇到错误时自动转发到下一个实例
      proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    }
  }
}

若使用PM2集群共享单端口(如仅3001),则upstream只需配置server localhost:3001;即可,PM2内部负责实例间负载均衡。

3. 零停机部署(解决部署Bad Gateway)

使用PM2的reload命令替代restart,实现滚动重启:

pm2 reload ecosystem.config.js

reload会逐个重启集群中的实例,重启单个实例时,PM2会将流量临时转移到其他正常实例,避免服务中断,彻底解决部署时的Bad Gateway问题。

验证配置:

nginx -t # 检查Nginx配置语法
systemctl reload nginx # 重载Nginx配置

内容的提问来源于stack exchange,提问作者Nikolay kitsul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:17:13