系统化的Node.js服务器搭建攻略
一、开发环境搭建
1. 安装Node.js最新LTS版本
- 官网下载:访问Node.js官网下载对应系统的LTS版本(截至2025年6月,最新LTS为v22.15.0)
- 包管理工具:
- npm:随Node.js自动安装,使用 npm -v 验证
- yarn:推荐安装最新版本: npm install -g yarn
2. 初始化项目
mkdir my-node-server
cd my-node-server
npm init -y # 生成package.json
3. 核心依赖安装
npm install express cors dotenv # 基础框架与工具
npm install mongoose # 数据库支持(可选)
npm install socket.io # 实时通信(可选)
npm install pm2 -g # 进程管理(生产环境)
二、基础服务器构建
1. 最小化Express服务器
// app.js
import express from 'express';
const app = express();
const port = process.env.PORT || 3000;
// 中间件配置
app.use(express.json()); // 解析JSON请求体
app.use(cors()); // 处理跨域请求
// 路由示例
app.get('/', (req, res) => {
res.send('Node.js服务器运行中!');
});
app.listen(port, () => {
console.log(`服务器运行于 http://localhost:${port}`);
});
2. 环境变量管理
创建 .env 文件:
NODE_ENV=development
PORT=3000
DB_URI=mongodb://localhost:27017/mydb
在代码中加载:
import dotenv from 'dotenv';
dotenv.config();
3. 数据库集成(MongoDB示例)
import mongoose from 'mongoose';
mongoose.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('数据库连接成功');
}).catch(err => {
console.error('数据库连接失败:', err);
});
三、进阶功能扩展
1. 实时通信(Socket.IO)
// 服务器端
import { createServer } from 'http';
import { Server } from 'socket.io';
const httpServer = createServer(app);
const io = new Server(httpServer);
io.on('connection', (socket) => {
console.log('客户端连接:', socket.id);
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('客户端断开');
});
});
httpServer.listen(3001, () => {
console.log('Socket.IO服务器运行于 http://localhost:3001');
});
2. 安全增强
- HTTPS配置:
import https from 'https';
import fs from 'fs';
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
https.createServer(options, app).listen(443);
- 输入验证:
import Joi from 'joi';
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(6).required()
});
app.post('/register', (req, res) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
// 处理注册逻辑
});
3. 错误处理
// 全局错误处理中间件
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('服务器内部错误!');
});
// 未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
console.error('未处理的Promise拒绝:', reason);
promise.catch(() => {}); // 防止无限循环
});
四、生产环境部署
1. 进程管理(PM2)
- 安装: npm install pm2 -g
- 启动应用:
pm2 start app.js --name "node-server"
pm2 save # 保存进程列表
pm2 startup # 配置开机自启
- 监控:
pm2 monit # 实时监控资源使用
pm2 logs # 查看日志
2. 容器化部署(Docker)
Dockerfile示例:
FROM node:22.15.0-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
构建与运行:
docker build -t node-server .
docker run -p 3000:3000 -d node-server
3. 云平台部署
- 阿里云ECS:
1. 选择Ubuntu 22.04 LTS镜像
2. 安装Node.js(使用NVM管理版本):
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 22
3. 配置安全组规则开放3000端口
4. 部署应用并启动PM2
- Vercel:
1. 上传代码到GitHub
2. 在Vercel控制台导入项目
3. 自动检测Node.js环境并部署
五、性能优化策略
1. 负载均衡
- PM2集群模式:
pm2 start app.js -i max # 根据CPU核心数自动启动进程
2. 缓存机制
- 内存缓存:
import cache from 'memory-cache';
app.get('/data', (req, res) => {
const cachedData = cache.get('data');
if (cachedData) {
return res.json(cachedData);
}
// 从数据库获取数据并缓存
const freshData = db.query('SELECT * FROM data');
cache.put('data', freshData, 300000); // 缓存5分钟
res.json(freshData);
});
3. 静态资源优化
- 使用Nginx作为反向代理:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /static/ {
root /path/to/static/files;
gzip on;
gzip_types text/css text/javascript image/png;
}
}
六、监控与日志
1. 日志系统
- Winston配置:
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
2. 性能监控
- 使用Sentry:
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: 'YOUR_DSN',
environment: process.env.NODE_ENV
});
app.use(Sentry.Handlers.errorHandler());
七、安全最佳实践
1. 输入验证:使用Joi或express-validator对所有用户输入进行校验
2. 密码安全:
import bcrypt from 'bcrypt';
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
3. 防止XSS攻击:
import sanitizeHtml from 'sanitize-html';
const cleanInput = sanitizeHtml(req.body.comment, {
allowedTags: [],
allowedAttributes: {}
});
4. HTTPS强制使用:
app.enable('trust proxy');
app.use((req, res, next) => {
if (req.secure) next();
else res.redirect(`https://${req.headers.host}${req.url}`);
});
八、持续集成与测试
1. 单元测试(Jest)
测试文件示例:
// app.test.js
import request from 'supertest';
import app from './app';
describe('GET /', () => {
it('返回200状态码', async () => {
const response = await request(app).get('/');
expect(response.statusCode).toBe(200);
});
});
运行测试:
npm test # 需要在package.json中配置"test": "jest"
2. CI/CD配置(GitHub Actions)
workflow文件:
name: Node.js CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm install
- run: npm test
九、版本控制与协作
1. Git分支策略:
- main :生产环境分支
- develop :开发主分支
- 功能分支:基于 develop 创建,命名如 feature/add-login
2. 代码审查:
- 使用GitHub Pull Requests进行代码审查
- 强制要求至少1人批准才能合并
3. 依赖管理:
- 使用 npm audit 检查依赖漏洞
- 定期更新依赖: npm outdated && npm update
十、项目结构推荐
project/
├── src/
│ ├── app.js # 主入口
│ ├── routes/ # 路由模块
│ │ └── api.js
│ ├── controllers/ # 控制器
│ │ └── user.js
│ ├── models/ # 数据模型(可选)
│ │ └── User.js
│ ├── middleware/ # 中间件
│ │ └── auth.js
│ └── config/ # 配置文件
│ └── index.js
├── tests/ # 测试目录
├── public/ # 静态资源
├── .env # 环境变量
├── Dockerfile # Docker配置
├── package.json
└── README.md