一、模块化开发规范与基础架构
1.1 模块化设计原则
NestJS采用模块化架构设计,每个功能模块应包含完整的MVC结构:
- 模块声明:通过
@Module()装饰器定义模块边界 - 分层结构:
src/├── users/ # 功能模块目录│ ├── dto/ # 数据传输对象│ ├── entities/ # 数据库实体│ ├── users.controller.ts│ ├── users.service.ts│ └── users.module.ts└── app.module.ts # 根模块
1.2 核心组件开发
以用户模块为例展示完整实现:
// users.controller.ts@Controller('users')export class UsersController {constructor(private readonly usersService: UsersService) {}@Get()async findAll() {return await this.usersService.findAll();}}// users.service.ts@Injectable()export class UsersService {findAll(): Promise<User[]> {return []; // 实际应连接数据库}}
二、HTTPS证书配置全流程
2.1 证书获取与准备
生产环境建议使用正规CA机构颁发的证书,开发环境可使用自签名证书:
# 生成自签名证书(开发环境)openssl req -x509 -newkey rsa:4096 -nodes \-keyout key.pem -out cert.pem -days 365
2.2 NestJS HTTPS配置
在main.ts中配置HTTPS服务:
import * as fs from 'fs';import * as https from 'https';async function bootstrap() {const httpsOptions = {key: fs.readFileSync('./key.pem'),cert: fs.readFileSync('./cert.pem'),// 可选:HTTP/2支持// alpnProtocols: ['h2', 'http/1.1']};const app = await NestFactory.create(AppModule, {httpsOptions,cors: true});await app.listen(443);}
2.3 证书自动续期方案
对于Let’s Encrypt等短期证书,建议配置自动续期:
- 安装Certbot工具
- 创建定时任务:
# 每天检查证书更新0 0 * * * certbot renew --quiet --deploy-hook "systemctl restart pm2"
三、PM2进程守护实践
3.1 生产环境部署方案
PM2提供完整的进程管理功能,包括:
- 进程守护
- 负载均衡
- 日志管理
- 性能监控
安装与基础配置:
npm install pm2 -gpm2 init # 生成生态文件
3.2 配置文件详解
ecosystem.config.js示例:
module.exports = {apps: [{name: 'nest-app',script: 'dist/main.js',instances: 'max', // 或指定数字exec_mode: 'cluster',env: {NODE_ENV: 'production',PORT: 443},error_file: './logs/err.log',out_file: './logs/out.log',merge_logs: true,log_date_format: 'YYYY-MM-DD HH:mm Z'}]};
3.3 常用运维命令
# 启动应用pm2 start ecosystem.config.js# 查看状态pm2 list# 日志管理pm2 logs --lines 100 # 查看最近100行日志pm2 flush # 清空日志# 性能监控pm2 monit
四、完整部署流程
4.1 环境准备检查清单
- Node.js v16+环境
- 数据库连接配置
- 防火墙开放443端口
- 域名DNS解析正确
- 系统资源监控工具
4.2 自动化部署脚本
#!/bin/bash# 依赖安装npm install --production# 构建生产包npm run build# 证书更新检查if [ -f "/etc/letsencrypt/live/example.com/fullchain.pem" ]; thencp /etc/letsencrypt/live/example.com/* /path/to/certs/fi# 启动应用pm2 restart ecosystem.config.js --update-env# 健康检查curl -I https://localhost
4.3 监控告警配置
建议集成主流监控系统:
- 日志收集:ELK Stack或行业常见日志服务
- 性能指标:Prometheus + Grafana
- 告警通知:Webhook或邮件通知
五、常见问题解决方案
5.1 HTTPS相关问题
- 证书无效:检查系统时间是否正确
- 混合内容警告:确保所有资源都通过HTTPS加载
- SNI支持:多域名证书需要服务器支持SNI
5.2 PM2常见问题
- 内存泄漏:配置
max_memory_restart参数 - 进程崩溃:设置
--watch参数自动重启 - 日志轮转:配置
logrotate或使用日志服务
5.3 性能优化建议
- 启用HTTP/2协议
- 配置连接池
- 使用CDN加速静态资源
- 数据库连接优化
六、安全加固措施
6.1 安全头配置
// main.tsapp.use(helmet()); // 自动添加安全头
6.2 速率限制
import { ThrottlerModule } from '@nestjs/throttler';@Module({imports: [ThrottlerModule.forRoot({ttl: 60,limit: 100})]})
6.3 定期安全审计
- 依赖项漏洞扫描
- 代码安全审查
- 渗透测试
通过以上系统化的部署方案,开发者可以构建出安全可靠、易于维护的NestJS生产环境。实际部署时,建议先在测试环境验证完整流程,再逐步迁移到生产环境。对于大型应用,可考虑使用容器化部署方案进一步简化运维工作。