【问题标题】:Cannot connect to remote Database instance from my docker container, however can connect from my host computer无法从我的 docker 容器连接到远程数据库实例,但是可以从我的主机连接
【发布时间】:2021-01-26 20:17:46
【问题描述】:

我从 docker 容器连接到远程数据库实例时遇到问题。

我有一个 Docker 容器,里面有一段简单的 Python 代码,可以连接到远程 MongoDB 实例

    client = MongoClient('mongodb-example_conn_string.com')
    db = client.test_db
    collection = db.test_collection
    print(collection.find_one())

我可以从我的主机(运行 Linux Mint 20 的笔记本电脑)上运行这段代码,它会按预期打印结果。

当我为此脚本和 Docker Run then image 构建 Docker 映像 (python:3.6.10-alpine) 时,我收到一条错误消息。 Container 正在主机笔记本电脑上运行。

例如

docker build . -t py_connection_test
docker run --rm py_connection_test run

我收到此错误

pymongo.errors.ServerSelectionTimeoutError: mongodb-example_conn_string.com:27017: [Errno -2] Name does not resolve, Timeout: 30s, Topology Description: <TopologyDescription id: 60106f40288b81e007fe75a8, topology_type: Single, servers: [<ServerDescription ('mongodb-example_conn_string.com', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('mongodb-example_conn_string.com:27017: [Errno -2] Name does not resolve',)>]>

MongoDB 远程实例是工作中的内部数据库,需要 VPN(使用 OpenVPN)才能访问它。我在主机和 docker 容器上使用了 traceroute 来确认网络流量是通过 VPN 路由的,那里似乎一切都很好。

我试过 Docker Run with flag

--network="host"

但同样的事情发生

我对此摸不着头脑,为什么相同的连接 url 在这两种情况下都不起作用?有什么我遗漏的简单事情吗?

【问题讨论】:

  • 我认为是 DNS 问题。见this
  • @Max 感谢您为我指出正确的方向,我的 /etc/resolv.conf 文件有问题

标签: python mongodb docker networking openvpn


【解决方案1】:

我已经解决了这个问题,感谢 Max 指点我查看 DNS。

我的问题是 Docker 容器正在接收的主机上的 /etc/resolv.conf 文件有问题。它包含 2 个名称服务器条目

在我的情况下,我可以在我的主机上创建文件 /etc/docker/daemon.json 并在那里添加我的 dns 条目,以便容器在运行时提取。例如添加行:

{
     "dns": ["172.31.0.2"]
}

编辑/创建此文件需要重启 Docker 服务

我从https://l-lin.github.io/post/2018/2018-09-03-docker_ubuntu_18_dns/得到了一些有用的提示

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多