搬瓦工部署 Nuxt.js Vue SSR 应用教程
Nuxt.js 是基于 Vue.js 的全栈框架,提供服务端渲染(SSR)、静态站点生成(SSG)和混合渲染等多种模式。Nuxt 3 基于 Vue 3 和 Nitro 引擎构建,性能和开发体验都有显著提升。本文将介绍如何在搬瓦工 VPS 上部署 Nuxt 3 应用。购买搬瓦工 VPS 请参考 全部方案,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。
一、环境准备
apt update && apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs git
npm install -g pm2
二、创建 Nuxt 3 项目
cd /opt
npx nuxi@latest init myapp
cd myapp
npm install
2.1 配置 nuxt.config.ts
cat > /opt/myapp/nuxt.config.ts << 'EOF'
export default defineNuxtConfig({
devtools: { enabled: false },
app: {
head: {
title: '我的 Nuxt 应用',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ name: 'description', content: '基于 Nuxt 3 构建的 Web 应用' }
]
}
},
nitro: {
preset: 'node-server'
}
})
EOF
三、开发与构建
3.1 SSR 模式构建
npm run build
构建产物在 .output/ 目录中,包含服务端和客户端代码。
3.2 静态模式构建
# 如果选择纯静态模式
npm run generate
四、PM2 运行 SSR 服务
cat > /opt/myapp/ecosystem.config.js << 'EOF'
module.exports = {
apps: [{
name: 'nuxt-app',
script: './.output/server/index.mjs',
cwd: '/opt/myapp',
env: {
NODE_ENV: 'production',
NITRO_PORT: 3000,
NITRO_HOST: '127.0.0.1'
},
instances: 'max',
exec_mode: 'cluster',
autorestart: true,
max_memory_restart: '500M'
}]
};
EOF
pm2 start ecosystem.config.js
pm2 save
pm2 startup
五、Nginx 反向代理
apt install nginx -y
cat > /etc/nginx/sites-available/nuxt.conf << 'EOF'
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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_cache_bypass $http_upgrade;
}
location /_nuxt/ {
alias /opt/myapp/.output/public/_nuxt/;
expires 1y;
add_header Cache-Control "public, immutable";
}
}
EOF
ln -sf /etc/nginx/sites-available/nuxt.conf /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl restart nginx
六、SSL 证书与部署脚本
apt install certbot python3-certbot-nginx -y
certbot --nginx -d yourdomain.com
cat > /opt/myapp/deploy.sh << 'EOF'
#!/bin/bash
cd /opt/myapp
git pull origin main
npm install
npm run build
pm2 restart nuxt-app
echo "[$(date)] Nuxt app deployed"
EOF
chmod +x /opt/myapp/deploy.sh
七、常见问题
SSR 内存占用高
Nuxt SSR 模式会占用更多内存。PM2 cluster 模式可以充分利用多核 CPU。如果内存紧张,可以考虑使用静态生成模式(SSG)。
水合不匹配
服务端和客户端渲染不一致会导致水合错误。避免在组件中直接使用 window 或 document 等浏览器 API,改用 onMounted 钩子。
总结
Nuxt.js 是 Vue 生态中最成熟的全栈框架,SSR 模式能显著提升 SEO 和首屏加载速度。在搬瓦工 VPS 上配合 PM2 和 Nginx 部署运行稳定可靠。其他框架教程包括 SvelteKit、Remix、Astro 等。购买搬瓦工 VPS 请访问 bwh81.net,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。