Skip to content

部署指南

TIP

更具体的方案介绍可以加作者微信 cxzk_168

开发环境搭建

系统要求

  • Node.js 18.0 或更高版本
  • npm 9.0 或 yarn 1.22 或更高版本
  • Git 2.0 或更高版本

本地开发环境

1. 安装依赖

bash
# 使用 npm
npm install

# 或使用 yarn
yarn install

# 或使用 pnpm
pnpm install

4. 启动开发服务器

bash
pnpm dev

访问 http://localhost:3000 查看应用。

生产环境部署

Docker 部署

Dockerfile

dockerfile
# 多阶段构建
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:18-alpine AS runner
WORKDIR /app

ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

CMD ["node", "server.js"]

Docker Compose

yaml
version: '3.8'

services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- NEXT_PUBLIC_APP_NAME=多维表格编辑器
volumes:
- ./data:/app/data
restart: unless-stopped

nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- app
restart: unless-stopped

部署命令

bash
# 构建镜像
docker build -t multi-table-editor .

# 运行容器
docker run -p 3000:3000 multi-table-editor

# 使用 Docker Compose
docker-compose up -d

传统服务器部署

使用 PM2

bash
# 安装 PM2
npm install -g pm2

# 构建项目
npm run build

# 启动应用
pm2 start npm --name "table-editor" -- start

# 保存 PM2 配置
pm2 save
pm2 startup

PM2 配置文件

javascript
// ecosystem.config.js
module.exports = {
apps: [{
name: 'pxcharts',
script: 'npm',
args: 'start',
cwd: '/path/to/your/app',
env: {
NODE_ENV: 'production',
PORT: 3000
},
instances: 'max',
exec_mode: 'cluster',
watch: false,
max_memory_restart: '1G',
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log',
time: true
}]
}

性能优化

1. 构建优化

Next.js 配置

javascript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
// 启用 SWC 编译器
swcMinify: true,

// 启用实验性功能
experimental: {
appDir: true,
serverComponentsExternalPackages: ['@prisma/client']
},

// 图片优化
images: {
domains: ['xxx.com'],
formats: ['image/webp', 'image/avif']
},

// 压缩配置
compress: true,

// 静态文件优化
assetPrefix: process.env.NODE_ENV === 'production' ? '/static' : '',

// Webpack 配置
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// 优化包大小
config.optimization.splitChunks = {
    chunks: 'all',
    cacheGroups: {
        vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
        },
   },
}

    return config
},
}

module.exports = nextConfig

2. 缓存策略

HTTP 缓存头

javascript
// next.config.js
const nextConfig = {
    async headers() {
        return [
            {
                source: '/static/(.*)',
                headers: [
                    {
                        key: 'Cache-Control',
                        value: 'public, max-age=31536000, immutable',
                    },
                ],
           },
            {
                source: '/(.*)',
                headers: [
                    {
                        key: 'X-Content-Type-Options',
                        value: 'nosniff',
                    },
                    {
                        key: 'X-Frame-Options',
                        value: 'DENY',
                    },
                    {
                        key: 'X-XSS-Protection',
                        value: '1; mode=block',
                    },
                ],
            },
        ]
    },
}

Service Worker

javascript
// public/sw.js
const CACHE_NAME = 'table-editor-v1'
const urlsToCache = [
    '/',
    '/static/js/bundle.js',
    '/static/css/main.css',
]

self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => cache.addAll(urlsToCache))
        )
})

self.addEventListener('fetch', (event) => {
    event.respondWith(
        caches.match(event.request)
            .then((response) => {
                if (response) {
                    return response
                }
                return fetch(event.request)
             })
        )
})

3. CDN 配置

Cloudflare 配置

javascript
// 页面规则
const pageRules = [
{
    url: "*.js",
    settings: {
        cache_level: "cache_everything",
        edge_cache_ttl: 31536000
    }
},
{
    url: "*.css",
    settings: {
        cache_level: "cache_everything",
        edge_cache_ttl: 31536000
    }
}
]

故障排除

常见问题

1. 构建失败

bash
# 清理缓存
rm -rf .next
rm -rf node_modules
npm install

# 检查 Node.js 版本
node --version  # 应该 >= 18.0.0

2. 内存不足

bash
# 增加 Node.js 内存限制
NODE_OPTIONS="--max-old-space-size=4096" npm run build

3. 端口冲突

bash
# 使用不同端口
PORT=3001 npm run dev

调试工具

1. 开发者工具

javascript
// 启用 React DevTools
if (process.env.NODE_ENV === 'development') {
import('react-devtools')
}

2. 性能分析

bash
# 分析包大小
npm run analyze

# 性能测试
npm run lighthouse

让技术更平权,致力于高性价办公协同解决方案