How to connect to mongodb from a different container

This is the main docker-compose file
version: “2”
volumes:
mongo-data:
Logs:
services:
wifi-connect:
build:
context: ./wifi-connect
dockerfile: Dockerfile.template
network_mode: “host”
labels:
io.balena.features.dbus: “1”
cap_add:
- net_admin
environment:
DBUS_SYSTEM_BUS_ADDRESS: “unix:path=/host/run/dbus/system_bus_socket”
db:
build:
context: ./db
dockerfile: Dockerfile.template
volumes:
- “mongo-data:/data/db”
network_mode: “host”
env_file:
- ./.env
environment:
MONGO_INITDB_ROOT_USERNAME: {MONGO_INITDB_ROOT_USERNAME} MONGO_INITDB_ROOT_PASSWORD: {MONGO_INITDB_ROOT_PASSWORD}
beacon:
privileged: true
build:
context: ./beacon
dockerfile: Dockerfile.template
labels:
io.balena.features.dbus: “1”
network_mode: “host”
cap_add:
- sys_admin
- net_admin
- sys_module
volumes:
- “Logs:/Logs”
env_file:
- ./.env
links:
- db

and in the python script this is what I am using to connect to the mongo container
client = MongoClient("mongodbv://root:rootpassword@db:27017")

But for some unknown reason I keep on getting -
pymongo.errors.ServerSelectionTimeoutError: db:27017: [Errno -5] No address associated with hostname, Timeout: 30s, Topology Description: <TopologyDescription id: 602bafb04da18cf5c68caea3, topology_type: Single, servers: [<ServerDescription ('db', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('db:27017: [Errno -5] No address associated with hostname')>]>

Hello, the error you get is about No address associated with hostname, ... <ServerDescription ('db', 27017) This is because when you do client = MongoClient("mongodbv://root:rootpassword@db:27017") it tries to reach the mongodb server at db:27017 but the client doesn’t know what the hostname db is. When you run a container in network_mode: host, the network namespace of the container is shared with the host, in practice this means that if you have a service running on port 123 in such a container, you can access it from the host (and other containers in host mode) at localhost:123.

So try changing the connection to client = MongoClient("mongodbv://root:rootpassword@localhost:27017") and let me know if you manage to connect to it successfully.