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

在AWS EC2的Docker MongoDB中启用TLS并配置域名访问

为Docker部署的MongoDB启用TLS加密并配置自定义域名连接

一、启用MongoDB TLS加密

1. 获取SSL证书

  • 生产环境推荐(可信证书):用Let's Encrypt生成免费证书(前提是你已拥有自定义域名):
    在EC2实例(以Ubuntu/Debian为例)安装certbot:

    sudo apt update && sudo apt install certbot -y
    

    生成证书(需确保域名已解析到EC2公网IP,且安全组开放80端口):

    sudo certbot certonly --standalone -d db.example.com
    

    证书文件默认存放在/etc/letsencrypt/live/db.example.com/,包含fullchain.pem(证书链)和privkey.pem(私钥)。

  • 测试环境可选(自签证书):

    openssl req -x509 -newkey rsa:4096 -keyout mongodb.key -out mongodb.crt -days 365 -nodes -subj "/CN=db.example.com"
    cat mongodb.key mongodb.crt > mongodb.pem
    

2. 配置MongoDB容器

  • 创建本地目录存放证书,调整权限适配MongoDB容器用户:

    sudo mkdir -p /opt/mongodb/certs
    # 若用Let's Encrypt证书
    sudo cp /etc/letsencrypt/live/db.example.com/fullchain.pem /opt/mongodb/certs/
    sudo cp /etc/letsencrypt/live/db.example.com/privkey.pem /opt/mongodb/certs/
    # 若用自签证书,替换为对应文件路径
    # sudo cp mongodb.pem /opt/mongodb/certs/
    sudo chown -R 999:999 /opt/mongodb/certs  # MongoDB容器默认使用UID/GID 999
    
  • 方式1:用命令行参数启动容器:

    docker run -d \
      --name mongodb \
      -p 27017:27017 \
      -v /opt/mongodb/data:/data/db \
      -v /opt/mongodb/certs:/certs \
      mongo:latest \
      --tlsMode requireTLS \
      --tlsCertificateKeyFile /certs/privkey.pem \
      --tlsCAFile /certs/fullchain.pem
    
  • 方式2:用配置文件启动(更易维护):
    创建/opt/mongodb/mongod.conf配置文件:

    net:
      port: 27017
      tls:
        mode: requireTLS
        certificateKeyFile: /certs/privkey.pem
        CAFile: /certs/fullchain.pem
    storage:
      dbPath: /data/db
    

    启动容器:

    docker run -d \
      --name mongodb \
      -p 27017:27017 \
      -v /opt/mongodb/data:/data/db \
      -v /opt/mongodb/certs:/certs \
      -v /opt/mongodb/mongod.conf:/etc/mongod.conf \
      mongo:latest -f /etc/mongod.conf
    

3. 验证TLS连接

用自定义域名连接,添加--tls参数:

mongosh "mongodb://db.example.com:27017" --tls

如果是自签证书,需临时跳过证书验证(仅测试用):

mongosh "mongodb://db.example.com:27017" --tls --tlsAllowInvalidCertificates

二、配置自定义域名作为MongoDB端点

  1. 解析域名到EC2公网IP:
    在你的域名服务商控制台,添加一条A记录:

    • 主机记录:db
    • 记录值:EC2实例的公网IP
    • TTL:建议设置为300秒(5分钟)
  2. 确保证书与域名匹配:
    证书的Common Name(CN)或Subject Alternative Name(SAN)必须包含db.example.com,否则TLS连接会触发域名不匹配错误。Let's Encrypt证书会自动匹配域名,自签证书需在生成时指定/CN=db.example.com。

  3. 验证域名解析:

    nslookup db.example.com
    

    输出应显示你EC2实例的公网IP。

关键注意事项

  • 安全组配置:EC2安全组仅允许信任的IP访问27017端口,避免开放0.0.0.0/0。
  • 证书续期:Let's Encrypt证书有效期90天,添加自动续期任务:
    sudo crontab -e
    # 添加以下内容,每天凌晨3点自动续期并重启MongoDB
    0 3 * * * certbot renew --quiet && docker restart mongodb
    
  • 额外安全加固:生产环境建议启用MongoDB身份验证(添加--auth启动参数),结合TLS实现双重安全保障。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:40:49