连接两个容器 MongoDB + Python 项目
Connecting two containers MongoDB + Python project
我正在尝试连接两个容器,其中一个正在使用 pymongo,我想从一个容器内部连接到第二个容器,我可以从我 运行 docker 打开,但我无法从一个容器连接到另一个容器,我已经尝试了所有可能的解决方案,但我确信我遗漏了一些东西:
docker-compose.yaml
version: "3"
networks:
shared:
driver: bridge
services:
application:
environment:
....
image: application:latest
ports:
....
volumes:
....
depends_on:
- mongo
networks:
- shared
mongo:
image: mongo:4.2-bionic
ports:
- "27017:27017"
networks:
- shared
连接:
def get_connection():
client = MongoClient('localhost', 27017)
database = client.database.beacons
return database
错误:
Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 621d188d8169b99b9cfc4c5e, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>
docker-compose 网络中的容器由其服务名称引用,因此在您的 pymongo 连接中使用:
client = MongoClient('mongo', 27017)
我正在尝试连接两个容器,其中一个正在使用 pymongo,我想从一个容器内部连接到第二个容器,我可以从我 运行 docker 打开,但我无法从一个容器连接到另一个容器,我已经尝试了所有可能的解决方案,但我确信我遗漏了一些东西:
docker-compose.yaml
version: "3"
networks:
shared:
driver: bridge
services:
application:
environment:
....
image: application:latest
ports:
....
volumes:
....
depends_on:
- mongo
networks:
- shared
mongo:
image: mongo:4.2-bionic
ports:
- "27017:27017"
networks:
- shared
连接:
def get_connection():
client = MongoClient('localhost', 27017)
database = client.database.beacons
return database
错误:
Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 621d188d8169b99b9cfc4c5e, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>
docker-compose 网络中的容器由其服务名称引用,因此在您的 pymongo 连接中使用:
client = MongoClient('mongo', 27017)