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

如何在Azure Web App部署多环境(开发/测试/生产)的Next.js 13应用

问题描述

尝试通过Azure自托管部署带有多环境配置的Next.js 13应用,已配置server.js、自定义web.config和包含多环境构建脚本的package.json,但部署失败,目标是实现多环境下的成功部署。


配置文件详情

server.js

const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 3001
const app = next({ dev,port })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
  const server = express()
  server.get('/p/:id', (req, res) => {
    const actualPage = '/post'
    const queryParams = { title: req.params.id }
    app.render(req, res, actualPage, queryParams)
  })
  server.get('*', (req, res) => {
    return handle(req, res)
  })

server.listen(port, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:' + port)
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

web.config

<?xml version="1.0" encoding="utf-8"?><!-- This configuration file is required if iisnode is used to run node processes behind IIS or IIS Express. For more information, visit: https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config--><configuration> <system.webServer> <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support --> <webSocket enabled="false" /> <handlers> <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module --> <add name="iisnode" path="server.js" verb="*" modules="iisnode"/> </handlers> <rewrite> <rules> <!-- Do not interfere with requests for node-inspector debugging --> <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true"> <match url="^server.js/debug[/]?" /> </rule> <!-- First we consider whether the incoming URL matches a physical file in the /public folder --> <rule name="StaticContent"> <action type="Rewrite" url="public{REQUEST_URI}"/> </rule> <!-- All other URLs are mapped to the node.js site entry point --> <rule name="DynamicContent"> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/> </conditions> <action type="Rewrite" url="server.js"/> </rule> </rules> </rewrite> <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it --> <security> <requestFiltering> <hiddenSegments> <remove segment="bin"/> </hiddenSegments> </requestFiltering> </security> <!-- Make sure error responses are left untouched --> <httpErrors existingResponse="PassThrough" /> <!-- You can control how Node is hosted within IIS using the following options: * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server * node_env: will be propagated to node as NODE_ENV environment variable * debuggingEnabled - controls whether the built-in debugger is enabled See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options --> <!--<iisnode watchedFiles="web.config;*.js"/>--> </system.webServer></configuration>

package.json

{
  "name": "quickview",
  "version": "0.1.0",
  "private": true,
  "main": "server.js",
  "scripts": {
    "buildDev": "env-cmd -f .env.development next build",
    "buildStaging": "env-cmd -f .env.staging next build",
    "buildProd": "env-cmd -f .env.production next build",
    "build": "next build",
    "start": "node server.js",
    "lint": "next lint",
    "startProd": "node server.js",
    "format": "prettier  --write \"src/**/*.{js,jsx,ts,tsx}\""
  },
  // 注:原JSON未闭合,部署时需确保文件格式完整
}

部署错误

部署错误截图


解决方案

1. 修复server.js的Next.js 13适配问题

Next.js 13中自定义服务器需确保环境变量正确传递,修改NODE_ENV的判断逻辑,同时在Azure门户的应用服务>配置>应用程序设置中手动添加NODE_ENV变量(对应环境设为development/staging/production),避免部署时dev模式误启:

// 确保port参数传递格式明确
const app = next({ dev, port: port })

2. 调整web.config适配Next.js静态资源

Next.js 13的静态资源默认输出到.next/static,修改StaticContent规则并补充路由适配:

<rewrite>
  <rules>
    <!-- 保留NodeInspector规则 -->
    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="^server.js/debug[/]?" />
    </rule>
    <!-- 适配Next.js静态资源路径 -->
    <rule name="NextStaticContent">
      <match url="^static/(.*)" />
      <action type="Rewrite" url=".next/static/{R:1}"/>
    </rule>
    <!-- 处理Next.js路由 -->
    <rule name="NextJS Routes" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="server.js" />
    </rule>
  </rules>
</rewrite>
<!-- 启用iisnode环境变量传递和文件监听 -->
<iisnode watchedFiles="web.config;*.js;.next/**/*.js" node_env="%NODE_ENV%" />

3. 完善多环境构建与部署流程

  • 环境变量管理:敏感环境变量不要放入.env.*文件,直接在Azure对应环境的应用程序设置中添加;若使用本地文件,需确保部署包包含这些文件。
  • 脚本优化:修改package.json脚本,明确环境启动命令:
"scripts": {
  "buildDev": "env-cmd -f .env.development next build",
  "buildStaging": "env-cmd -f .env.staging next build",
  "buildProd": "env-cmd -f .env.production next build",
  "startDev": "NODE_ENV=development node server.js",
  "startStaging": "NODE_ENV=staging node server.js",
  "startProd": "NODE_ENV=production node server.js",
  // 保留其他原有脚本
}
  • 部署流水线配置:在Azure部署中心(如GitHub Actions)为不同环境配置独立任务,生产环境执行npm run buildProd && npm run startProd, staging环境对应执行buildStaging和startStaging。

4. 排查Azure部署依赖与权限

  • 确保Azure应用服务的Node.js版本与本地开发环境一致(应用服务>配置>常规设置中选择对应版本)。
  • 部署时启用Oryx自动构建,确保依赖正确安装(npm install --production)。
  • 查看应用服务>日志流>应用日志,获取详细错误信息,定位具体崩溃原因(如缺失依赖、环境变量未找到等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:32:16