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

AWS Lambda Layer部署Node.js Postgres客户端遇自签名证书链错误

解决Lambda Layer中Postgres RDS自签名证书链错误

问题根源

将Postgres客户端代码迁移到Lambda Layer后,出现self-signed certificate in certificate chain错误,原因是Layer环境中缺少AWS RDS的根证书,或者pg客户端无法自动找到系统证书路径,导致SSL证书验证失败。而直接在Lambda函数中运行时,函数环境默认包含了必要的证书配置。


解决方案

1. 配置RDS根证书(生产环境推荐)

AWS提供了RDS专用的根证书,将其打包到Layer并在代码中指定路径,即可完成证书验证:

  • 下载对应区域的RDS根证书文件(如rds-ca-2019-root.pem)
  • 将证书放入Layer的certs目录,Layer最终结构为:
    layer-content/
    ├── certs/
    │   └── rds-ca-2019-root.pem
    └── nodejs/
        └── node_modules/
            └── pg/
    
  • 修改pg客户端配置,指定证书路径:
    const pg = require('pg');
    const fs = require('fs');
    const path = require('path');
    
    // Lambda Layer的文件会挂载到/opt目录下
    const rdsCaPath = path.join('/opt', 'certs', 'rds-ca-2019-root.pem');
    
    let client = new pg.Client({
        host: db_info.host,
        user: db_info.username,
        database: db_info.dbName,
        password: db_info.password,
        port: db_info.port,
        ssl: {
            rejectUnauthorized: true,
            ca: fs.readFileSync(rdsCaPath).toString()
        }
    });
    client.connect();
    

2. 临时禁用证书验证(仅测试环境)

如果是测试环境,可临时关闭证书验证(生产环境禁止使用):

const pg = require('pg');

let client = new pg.Client({
    host: db_info.host,
    user: db_info.username,
    database: db_info.dbName,
    password: db_info.password,
    port: db_info.port,
    ssl: {
        rejectUnauthorized: false
    }
});
client.connect();

3. 确认Layer依赖打包正确

打包pg到Layer时,需确保依赖完整:

  • 在本地执行npm install pg --production安装生产依赖
  • 将node_modules目录放入Layer的nodejs目录下,确保Lambda能正确加载模块

内容的提问来源于stack exchange,提问作者James A Cubeta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:00:09