无法从我的 docker 容器连接到远程数据库实例,但是可以从我的主机连接
Cannot connect to remote Database instance from my docker container, however can connect from my host computer
我在从 docker 容器连接到远程数据库实例时遇到问题。
我有一个 Docker 容器,其中有一段简单的 Python 代码连接到远程 MongoDB 实例
client = MongoClient('mongodb-example_conn_string.com')
db = client.test_db
collection = db.test_collection
print(collection.find_one())
我可以从我的主机(笔记本电脑 运行ning Linux Mint 20)运行 这段代码,它会按预期打印结果。
当我为此脚本构建 Docker 图像 (python:3.6.10-alpine) 和 Docker 运行 图像时,我收到一条错误消息。 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 运行 标记
--network="host"
但同样的事情发生了
我正在摸不着头脑,为什么同一个连接 url 在这两种情况下都不起作用?我错过了什么简单的东西吗?
我已经解决了这个问题,感谢 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/
那里得到了一些有用的提示
我在从 docker 容器连接到远程数据库实例时遇到问题。
我有一个 Docker 容器,其中有一段简单的 Python 代码连接到远程 MongoDB 实例
client = MongoClient('mongodb-example_conn_string.com')
db = client.test_db
collection = db.test_collection
print(collection.find_one())
我可以从我的主机(笔记本电脑 运行ning Linux Mint 20)运行 这段代码,它会按预期打印结果。
当我为此脚本构建 Docker 图像 (python:3.6.10-alpine) 和 Docker 运行 图像时,我收到一条错误消息。 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 运行 标记
--network="host"
但同样的事情发生了
我正在摸不着头脑,为什么同一个连接 url 在这两种情况下都不起作用?我错过了什么简单的东西吗?
我已经解决了这个问题,感谢 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/
那里得到了一些有用的提示