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

MongoDB TLS证书主机名不匹配问题求助及修复方案咨询

MongoDB TLS证书主机名匹配问题及解决方案

问题背景

MongoDB遭两次入侵后,在VPS部署MongoDB TLS加密以提升安全性,执行连接命令时出现主机名/IP与证书备用名称不匹配的错误,使用--tlsAllowInvalidHostnames参数可临时绕过,但需要实现正确的TLS连接,同时要支持本地PC远程连接。

错误详情

执行连接命令:

mongosh localhost --tls --tlsCertificateKeyFile /etc/ssl/client.pem --tlsCAFile /etc/ssl/ca.pem

报错内容:

MongoServerSelectionError: Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the cert's list

当前证书配置

生成证书时的备用名称配置片段:

openssl x509 -passin pass:password -sha256 -req -days 365 -in node1.csr -CA ca.pem -CAkey ca_private.pem -CAcreateserial -out node1-signed.crt -extensions v3_req -extfile <(
cat << EOF
[ v3_req ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = 127.0.0.1
DNS.2 = localhost
EOF
)

问题解答

1. 此情况是否正常?证书是否存在问题?

不正常,证书配置存在错误:你将127.0.0.1标记为DNS类型的备用名称,但它是IP地址,TLS校验时会将其视为DNS域名而非IP地址处理,因此客户端用127.0.0.1连接时,无法匹配证书中的DNS项,导致报错。

2. 修复方法

重新生成证书,将IP地址单独用IP类型配置,修改备用名称部分:

openssl x509 -passin pass:password -sha256 -req -days 365 -in node1.csr -CA ca.pem -CAkey ca_private.pem -CAcreateserial -out node1-signed.crt -extensions v3_req -extfile <(
cat << EOF
[ v3_req ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = localhost
IP.1 = 127.0.0.1
EOF
)

替换原有证书后重启MongoDB服务,即可无需--tlsAllowInvalidHostnames参数正常连接。

3. 本地PC远程连接的处理

要实现本地PC通过正确主机名连接,需完成以下操作:

  • 在证书备用名称中添加VPS的公网IP和公网域名(如有),示例配置:
[ alt_names ]
DNS.1 = localhost
DNS.2 = your-vps-domain.com # 替换为你的VPS域名
IP.1 = 127.0.0.1
IP.2 = x.x.x.x # 替换为VPS公网IP
  • 修改MongoDB配置文件,绑定公网IP并开启TLS:
net:
  port: 27017
  bindIp: 0.0.0.0 # 或指定为"127.0.0.1,x.x.x.x"
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/node1-signed.crt # 若为合并key与crt的pem文件,填写对应路径
    CAFile: /etc/ssl/ca.pem
  • 本地PC连接时,使用VPS的公网域名或IP作为地址,带上TLS参数:
mongosh your-vps-domain.com:27017 --tls --tlsCertificateKeyFile /path/to/local/client.pem --tlsCAFile /path/to/local/ca.pem

(若无需客户端证书认证,可移除--tlsCertificateKeyFile参数,根据实际认证配置调整)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:33:19