nestjs后端服务器部署https证书配置

7 阅读1分钟

可以去腾讯云或者阿里云申请3个月的免费证书之后替换就是

main.ts

import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { AppModule } from './app.module';
import express from 'express';
import { ExpressAdapter } from '@nestjs/platform-express';

async function bootstrap() {
  const server = express();
  const app = await NestFactory.create(AppModule, new ExpressAdapter(server));

  // SSL证书配置(添加错误处理)
  const sslKeyPath = '/var/yjst/ssl-zhengshu/pengfei.site.key';
  const sslCertPath = '/var/yjst/ssl-zhengshu/pengfei.site.crt';
  const sslCaPath = '/var/yjst/ssl-zhengshu/root_bundle.crt';

  let httpsOptions = null;
  try {
    if (fs.existsSync(sslKeyPath) && fs.existsSync(sslCertPath)) {
      httpsOptions = {
        key: fs.readFileSync(sslKeyPath),
        cert: fs.readFileSync(sslCertPath),
        ca: fs.readFileSync(sslCaPath),
      };
    } else {
      console.warn('SSL证书文件不存在,将仅启动HTTP服务');
    }
  } catch (error) {
    console.error('读取SSL证书失败:', error);
  }

  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
  app.setGlobalPrefix('api/v1');

  // 添加全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  // 启用CORS(如果需要)
  app.enableCors();

  // 初始化应用(但不监听端口)
  await app.init();

  const httpPort = 3000;
  const httpsPort = 443;

  // 启动HTTP服务
  const httpServer = http.createServer(server);
  httpServer.listen(httpPort, () => {
    console.log(`HTTP Server running on port ${httpPort}`);
  });

  // 启动HTTPS服务(如果证书存在)
  if (httpsOptions) {
    const httpsServer = https.createServer(httpsOptions, server);
    httpsServer.listen(httpsPort, () => {
      console.log(`HTTPS Server running on port ${httpsPort}`);
    });
  }

  // 优雅关闭
  process.on('SIGTERM', () => {
    console.log('Received SIGTERM, shutting down gracefully');
    httpServer.close(() => {
      process.exit(0);
    });
  });
}

bootstrap().catch((error) => {
  console.error('Application failed to start:', error);
  process.exit(1);
});