新手求助:如何在Heroku上部署NuxtJS前端与Django后端?
NuxtJS + Django 同部署到Heroku的可行方案
方案1:以Nuxt为主服务,代理Django API请求(适配Nuxt SSR)
让Nuxt作为对外暴露的主服务,将API请求转发到内部运行的Django服务,适配Heroku单端口限制。
- 配置Nuxt代理规则
在nuxt.config.ts中添加代理,将/api开头的请求转发到Django:
export default defineNuxtConfig({ nitro: { routeRules: { '/api/**': { proxy: `http://localhost:${process.env.DJANGO_PORT || 8000}/api/**` } } } })
- 设置Heroku构建顺序
先安装Node依赖构建Nuxt,再处理Python依赖:
heroku buildpacks:clear heroku buildpacks:add heroku/nodejs heroku buildpacks:add heroku/python
- 配置项目启动脚本
- 在
package.json中添加Nuxt构建和启动命令:
{ "scripts": { "build": "nuxt build", "start": "node .output/server/index.mjs" } }
- 在
requirements.txt中添加进程管理器honcho:
honcho gunicorn # 其他Django依赖...
- 编写Procfile
用honcho同时启动Nuxt和Django,指定各自监听端口:
release: python manage.py migrate web: honcho start nuxt django
在项目根目录创建.env文件(或在Heroku控制台设置环境变量):
DJANGO_PORT=8000 PORT=${PORT:-3000}
补充进程定义(honcho自动读取):
nuxt: npm start django: gunicorn backend.wsgi --bind 0.0.0.0:$DJANGO_PORT --log-file -
方案2:以Django为主服务,托管Nuxt静态文件(适配Nuxt静态生成)
如果Nuxt是静态生成模式(无需SSR),可直接将Nuxt产物放入Django静态目录,由Django统一处理请求。
- 配置Nuxt静态生成目录
修改nuxt.config.ts,将静态文件输出到Django静态目录:
export default defineNuxtConfig({ generate: { outDir: '../backend/static/nuxt' } })
- 配置Django静态文件与路由
- 在
settings.py中添加Nuxt静态目录:
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]
- 创建Django视图返回Nuxt首页:
from django.shortcuts import render def nuxt_index(request): return render(request, 'nuxt/index.html')
- 在
urls.py中路由所有非API请求到Nuxt页面:
from django.urls import path, re_path from .views import nuxt_index urlpatterns = [ path('api/', include('your_api_app.urls')), re_path(r'^.*$', nuxt_index), ]
- 配置构建与启动
- 在
package.json中添加postbuild命令,自动收集静态文件:
{ "scripts": { "build": "nuxt generate", "postbuild": "python manage.py collectstatic --noinput" } }
- Procfile只需启动Django:
release: python manage.py migrate web: gunicorn backend.wsgi --log-file -
方案3:修复Docker容器部署
若本地Docker可运行但Heroku部署失败,检查heroku.yml配置:
build: docker: web: Dockerfile run: web: honcho start nuxt django
确保Dockerfile为多阶段构建,正确安装依赖并构建Nuxt:
FROM node:18-alpine as nuxt-build WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build FROM python:3.11-slim WORKDIR /app COPY --from=nuxt-build /app/.output ./nuxt-output COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . . ENV DJANGO_PORT=8000 ENV PORT=3000 CMD ["honcho", "start", "nuxt", "django"]
执行容器部署命令:
heroku container:login heroku container:push web heroku container:release web
内容的提问来源于stack exchange,提问作者water_bottle
相关产品推荐
相关产品推荐

