Reputation: 456
I'm trying to connect to a mongoDB database inside a docker container but I'm getting this error message : "getaddrinfo ENOTFOUND mongo" and I have no idea what caused it. I'm still new to docker and I can't seem to find a solution to this problem.
Here is my docker-compose file:
version: '3.9'
services:
mongo:
image: mongo:latest
restart: always
container_name: mongodb
ports:
- '27017:27017'
volumes:
- mongodb:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: hazem
MONGO_INITDB_ROOT_PASSWORD: 123
MONGO_INITDB_DATABASE: DB
volumes:
mongodb: {}
and here is the function to connect to the DB :
export const connectDB = async () => {
try {
await mongoose.connect("mongodb://hazem:123@mongo:27017/DB");
console.log("connected to DB");
} catch (error: any) {
console.log(error.message);
// retry to connect after 5 seconds
setTimeout(connectDB, 5000);
}
};
Upvotes: 4
Views: 11825
Reputation: 2935
All I had to do was check the 'Direct connection' checkbox and it connected right away.
Upvotes: 18
Reputation: 10737
If your code runs on the host then the connection string should be:
mongodb://hazem:123@localhost:27017/DB
Your connection string is correct if it runs in a container, but then you need to make sure the container is on the same docker network as the database container.
Upvotes: 3