You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS连接AWS RDS PostgreSQL时SSL证书错误及配置疑问

解决AWS RDS PostgreSQL + TypeOrm SSL连接证书验证错误

问题原因

仅设置ssl: true时,TypeOrm会使用系统默认根证书链验证RDS证书,但RDS的CA证书不在默认链中,因此抛出self-signed certificate in certificate chain错误,需显式指定RDS专属CA证书完成验证。

解决方案步骤

1. 获取RDS CA证书

下载指定的rds-ca-rsa2048-g1.pem证书,可通过命令行直接获取:

curl -o rds-ca-rsa2048-g1.pem https://truststore.pki.rds.amazonaws.com/global/rds-ca-rsa2048-g1.pem

(注:若RDS实例在特定区域,也可下载对应区域的CA证书,全局证书适用于所有区域)

2. 本地开发环境配置

修改TypeOrm的SSL配置,显式指定CA证书内容:

import * as fs from 'fs';
import * as path from 'path';

TypeOrmModule.forRoot({
  type: 'postgres',
  host: envVar.POSTGRES_HOST,
  port: envVar.POSTGRES_PORT,
  username: envVar.POSTGRES_USER,
  password: envVar.POSTGRES_PASSWORD,
  database: envVar.POSTGRES_DB,
  ssl: {
    // 读取本地证书文件,路径根据项目结构调整
    ca: fs.readFileSync(path.join(__dirname, '../certificates/rds-ca-rsa2048-g1.pem')).toString(),
    rejectUnauthorized: true // 必须保持true,确保连接安全
  }
})

3. 证书存放与版本控制

  • 不要将证书文件加入版本控制:在.gitignore中添加规则:
    certificates/*.pem
    
  • 推荐添加初始化脚本:在package.json中加入prestart脚本,启动项目前自动下载证书:
    "scripts": {
      "prestart": "mkdir -p certificates && curl -o certificates/rds-ca-rsa2048-g1.pem https://truststore.pki.rds.amazonaws.com/global/rds-ca-rsa2048-g1.pem",
      "start": "node dist/main.js"
    }
    

4. 生产环境(Kubernetes)配置

推荐将证书存入Secret(权限控制更严格,符合安全最佳实践):

创建Secret

kubectl create secret generic rds-ca-cert --from-file=rds-ca-rsa2048-g1.pem=./rds-ca-rsa2048-g1.pem

在Deployment中挂载Secret

修改Deployment配置,将Secret挂载到容器内指定路径:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: your-app-deployment
spec:
  template:
    spec:
      containers:
        - name: your-app-container
          image: your-app-image:latest
          volumeMounts:
            - name: rds-ca-cert-volume
              mountPath: /app/certificates
              readOnly: true
      volumes:
        - name: rds-ca-cert-volume
          secret:
            secretName: rds-ca-cert

修改TypeOrm配置读取容器内证书

ssl: {
  ca: fs.readFileSync('/app/certificates/rds-ca-rsa2048-g1.pem').toString(),
  rejectUnauthorized: true
}

注意事项

  • 禁止设置rejectUnauthorized: false,这会关闭证书验证,导致SSL连接失去安全性。
  • 如果仍报错,检查证书路径是否正确,或确认下载的证书与RDS实例的CA版本匹配(可在RDS控制台查看实例使用的CA类型)。

内容的提问来源于stack exchange,提问作者Yahli Gitzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:15:08