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

经典Azure Pipeline部署Next.js至Windows服务器:PM2维持运行的问题

解决Next.js在Windows自托管服务器持续运行的方案

核心问题原因

你使用npm run start或pm2-runtime时,Azure Pipelines任务会绑定到启动的应用进程,只有进程退出任务才会结束,导致流水线一直处于运行状态。需要让应用启动命令脱离流水线的执行上下文,同时保证应用能在后台持续运行。

可行解决方案

方案1:将PM2配置为Windows服务(推荐)

通过pm2-windows-service把PM2注册为Windows系统服务,这样流水线任务结束后,应用仍能作为服务持续运行,且支持开机自启。

修改流水线步骤:

  1. 安装核心依赖与PM2服务包
npm install
npm install pm2 -g
npm install pm2-windows-service -g
  1. 初始化PM2服务(仅第一次部署时执行,可加条件判断避免重复执行)
pm2-service-install -n "NextJS-App" -s "C:\Program Files\nodejs\node.exe" -a "$(npm prefix -g)\node_modules\pm2\bin\pm2.js" -e "start ecosystem.config.js --env production"
  1. 每次部署时启动/重启应用
pm2 restart ecosystem.config.js --env production

注意:确保自托管代理的运行账户拥有注册Windows服务的权限。

方案2:用PowerShell后台启动进程

通过PowerShell的Start-Process命令,让应用启动命令在独立进程中运行,脱离流水线的任务进程:

替换原有的PM2启动步骤为:

Start-Process pm2 -ArgumentList "start ecosystem.config.js --env production" -NoNewWindow -PassThru

如果用npm run start则改为:

Start-Process npm -ArgumentList "run start" -WorkingDirectory "你的项目目录" -NoNewWindow -PassThru

此方式无需额外配置服务,但服务器重启后应用不会自动启动,适合临时测试场景。

方案3:修复iisnode配置错误

如果想继续使用iisnode,常见错误多源于配置不匹配,需确保:

  • 安装与Node版本(32/64位)匹配的iisnode
  • 在项目根目录配置正确的web.config:
<configuration>
  <system.webServer>
    <handlers>
      <add name="iisnode" path="server.js" verb="*" modules="iisnode" />
    </handlers>
    <rewrite>
      <rules>
        <rule name="NextJS反向代理">
          <match url="/*" />
          <action type="Rewrite" url="server.js" />
        </rule>
      </rules>
    </rewrite>
    <iisnode nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />
  </system.webServer>
</configuration>

注意:Next.js SSR项目需先构建生成server.js,或对应next start的入口文件。

流水线步骤优化建议

将分散的steps合并为一个步骤块,避免重复定义:

steps:
  - task: NodeTool@0
    displayName: '使用Node 20.x'
    inputs:
      versionSpec: 20.x

  - powershell: |
      npm install
      npm install pm2 -g
      npm install pm2-windows-service -g
      # 检查PM2服务是否已注册,未注册则初始化
      if (-not (Get-Service -Name "NextJS-App" -ErrorAction SilentlyContinue)) {
        pm2-service-install -n "NextJS-App" -s "C:\Program Files\nodejs\node.exe" -a "$(npm prefix -g)\node_modules\pm2\bin\pm2.js" -e "start ecosystem.config.js --env production"
      }
      pm2 restart ecosystem.config.js --env production
    workingDirectory: '你的项目目录'
    displayName: '安装依赖并启动/重启Next.js应用'
    env:
      HOME: ~

内容的提问来源于stack exchange,提问作者Mohamed Sayed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:00:23