NestJS全栈部署指南:HTTPS安全加固与PM2进程守护实践

一、模块化开发规范与基础架构

1.1 模块化设计原则

NestJS采用模块化架构设计,每个功能模块应包含完整的MVC结构:

  • 模块声明:通过@Module()装饰器定义模块边界
  • 分层结构
    1. src/
    2. ├── users/ # 功能模块目录
    3. ├── dto/ # 数据传输对象
    4. ├── entities/ # 数据库实体
    5. ├── users.controller.ts
    6. ├── users.service.ts
    7. └── users.module.ts
    8. └── app.module.ts # 根模块

1.2 核心组件开发

以用户模块为例展示完整实现:

  1. // users.controller.ts
  2. @Controller('users')
  3. export class UsersController {
  4. constructor(private readonly usersService: UsersService) {}
  5. @Get()
  6. async findAll() {
  7. return await this.usersService.findAll();
  8. }
  9. }
  10. // users.service.ts
  11. @Injectable()
  12. export class UsersService {
  13. findAll(): Promise<User[]> {
  14. return []; // 实际应连接数据库
  15. }
  16. }

二、HTTPS证书配置全流程

2.1 证书获取与准备

生产环境建议使用正规CA机构颁发的证书,开发环境可使用自签名证书:

  1. # 生成自签名证书(开发环境)
  2. openssl req -x509 -newkey rsa:4096 -nodes \
  3. -keyout key.pem -out cert.pem -days 365

2.2 NestJS HTTPS配置

main.ts中配置HTTPS服务:

  1. import * as fs from 'fs';
  2. import * as https from 'https';
  3. async function bootstrap() {
  4. const httpsOptions = {
  5. key: fs.readFileSync('./key.pem'),
  6. cert: fs.readFileSync('./cert.pem'),
  7. // 可选:HTTP/2支持
  8. // alpnProtocols: ['h2', 'http/1.1']
  9. };
  10. const app = await NestFactory.create(AppModule, {
  11. httpsOptions,
  12. cors: true
  13. });
  14. await app.listen(443);
  15. }

2.3 证书自动续期方案

对于Let’s Encrypt等短期证书,建议配置自动续期:

  1. 安装Certbot工具
  2. 创建定时任务:
    1. # 每天检查证书更新
    2. 0 0 * * * certbot renew --quiet --deploy-hook "systemctl restart pm2"

三、PM2进程守护实践

3.1 生产环境部署方案

PM2提供完整的进程管理功能,包括:

  • 进程守护
  • 负载均衡
  • 日志管理
  • 性能监控

安装与基础配置:

  1. npm install pm2 -g
  2. pm2 init # 生成生态文件

3.2 配置文件详解

ecosystem.config.js示例:

  1. module.exports = {
  2. apps: [{
  3. name: 'nest-app',
  4. script: 'dist/main.js',
  5. instances: 'max', // 或指定数字
  6. exec_mode: 'cluster',
  7. env: {
  8. NODE_ENV: 'production',
  9. PORT: 443
  10. },
  11. error_file: './logs/err.log',
  12. out_file: './logs/out.log',
  13. merge_logs: true,
  14. log_date_format: 'YYYY-MM-DD HH:mm Z'
  15. }]
  16. };

3.3 常用运维命令

  1. # 启动应用
  2. pm2 start ecosystem.config.js
  3. # 查看状态
  4. pm2 list
  5. # 日志管理
  6. pm2 logs --lines 100 # 查看最近100行日志
  7. pm2 flush # 清空日志
  8. # 性能监控
  9. pm2 monit

四、完整部署流程

4.1 环境准备检查清单

  1. Node.js v16+环境
  2. 数据库连接配置
  3. 防火墙开放443端口
  4. 域名DNS解析正确
  5. 系统资源监控工具

4.2 自动化部署脚本

  1. #!/bin/bash
  2. # 依赖安装
  3. npm install --production
  4. # 构建生产包
  5. npm run build
  6. # 证书更新检查
  7. if [ -f "/etc/letsencrypt/live/example.com/fullchain.pem" ]; then
  8. cp /etc/letsencrypt/live/example.com/* /path/to/certs/
  9. fi
  10. # 启动应用
  11. pm2 restart ecosystem.config.js --update-env
  12. # 健康检查
  13. curl -I https://localhost

4.3 监控告警配置

建议集成主流监控系统:

  1. 日志收集:ELK Stack或行业常见日志服务
  2. 性能指标:Prometheus + Grafana
  3. 告警通知:Webhook或邮件通知

五、常见问题解决方案

5.1 HTTPS相关问题

  • 证书无效:检查系统时间是否正确
  • 混合内容警告:确保所有资源都通过HTTPS加载
  • SNI支持:多域名证书需要服务器支持SNI

5.2 PM2常见问题

  • 内存泄漏:配置max_memory_restart参数
  • 进程崩溃:设置--watch参数自动重启
  • 日志轮转:配置logrotate或使用日志服务

5.3 性能优化建议

  1. 启用HTTP/2协议
  2. 配置连接池
  3. 使用CDN加速静态资源
  4. 数据库连接优化

六、安全加固措施

6.1 安全头配置

  1. // main.ts
  2. app.use(helmet()); // 自动添加安全头

6.2 速率限制

  1. import { ThrottlerModule } from '@nestjs/throttler';
  2. @Module({
  3. imports: [
  4. ThrottlerModule.forRoot({
  5. ttl: 60,
  6. limit: 100
  7. })
  8. ]
  9. })

6.3 定期安全审计

  1. 依赖项漏洞扫描
  2. 代码安全审查
  3. 渗透测试

通过以上系统化的部署方案,开发者可以构建出安全可靠、易于维护的NestJS生产环境。实际部署时,建议先在测试环境验证完整流程,再逐步迁移到生产环境。对于大型应用,可考虑使用容器化部署方案进一步简化运维工作。