diff --git a/ecosystem.config.js b/ecosystem.config.js index 985cfe2..0547e3c 100644 --- a/ecosystem.config.js +++ b/ecosystem.config.js @@ -7,11 +7,13 @@ module.exports = { exec_mode: 'fork', env: { NODE_ENV: 'production', - PORT: 4001 + PORT: 4001, + FRONTEND_PORT: 4002 }, env_production: { NODE_ENV: 'production', - PORT: 4001 + PORT: 4001, + FRONTEND_PORT: 4002 }, // 日志配置 log_file: './logs/combined.log', diff --git a/start-production.cjs b/start-production.cjs index 3749c67..f4b6ab8 100644 --- a/start-production.cjs +++ b/start-production.cjs @@ -1,46 +1,70 @@ const { spawn } = require('child_process'); const path = require('path'); +const express = require('express'); // 生产环境配置 -const PORT = process.env.PORT || 4001; +const API_PORT = process.env.PORT || 4001; +const FRONTEND_PORT = process.env.FRONTEND_PORT || 4002; const NODE_ENV = 'production'; // 设置环境变量 process.env.NODE_ENV = NODE_ENV; -process.env.PORT = PORT; +process.env.PORT = API_PORT; -console.log(`启动生产环境服务器,端口: ${PORT}`); +console.log(`启动生产环境服务器`); +console.log(`后端API端口: ${API_PORT}`); +console.log(`前端静态文件端口: ${FRONTEND_PORT}`); console.log(`工作目录: ${process.cwd()}`); -// 启动后端服务器 -const server = spawn('node', ['--import', 'tsx/esm', 'api/server.ts'], { +// 启动前端静态文件服务 +const app = express(); +app.use(express.static(path.join(__dirname, 'dist'))); +app.get('*', (req, res) => { + res.sendFile(path.join(__dirname, 'dist', 'index.html')); +}); + +const frontendServer = app.listen(FRONTEND_PORT, () => { + console.log(`前端静态文件服务已启动,端口: ${FRONTEND_PORT}`); +}); + +// 启动后端API服务器 +const apiServer = spawn('node', ['--import', 'tsx/esm', 'api/server.ts'], { stdio: 'inherit', env: { ...process.env, NODE_ENV: NODE_ENV, - PORT: PORT + PORT: API_PORT } }); -// 处理进程退出 -server.on('close', (code) => { - console.log(`服务器进程退出,退出码: ${code}`); +// 处理API服务器进程退出 +apiServer.on('close', (code) => { + console.log(`API服务器进程退出,退出码: ${code}`); + frontendServer.close(); process.exit(code); }); -// 处理错误 -server.on('error', (err) => { - console.error('启动服务器时发生错误:', err); +// 处理API服务器错误 +apiServer.on('error', (err) => { + console.error('启动API服务器时发生错误:', err); + frontendServer.close(); process.exit(1); }); // 优雅关闭 process.on('SIGINT', () => { console.log('\n收到 SIGINT 信号,正在关闭服务器...'); - server.kill('SIGINT'); + frontendServer.close(); + apiServer.kill('SIGINT'); }); process.on('SIGTERM', () => { console.log('\n收到 SIGTERM 信号,正在关闭服务器...'); - server.kill('SIGTERM'); + frontendServer.close(); + apiServer.kill('SIGTERM'); +}); + +// 处理前端服务器错误 +frontendServer.on('error', (err) => { + console.error('前端静态文件服务器错误:', err); }); \ No newline at end of file