docker container cannot connect to localhost mongodb
Solution 1
The problem here is that you're starting a docker container (a self contained environment) and then trying to reach localhost:27017
. However, localhost inside your container is not the same localhost as outside your container (on your host). There are two approaches you could take from this point:
- Instead of attempting to connect to
localhost:27017
, connect to your host's ip (something like 192.x.x.x or 10.x.x.x) - (Better option imo) dockerize your mongodb, then your services will be able to communicate with each other using docker dns. To do this, you would create a
docker-compose.yml
with one service being your app and the other being mongodb.
Solution 2
- When you try with
MONGO_URL=mongodb://192.168.0.198:27017/rocketchat
add that IP tobindIp
as well. - With localhost
MONGO_URL=mongodb://127.0.0.1:27017/rocketchat
I also recommend enabling security authorization in mongo config. Then set a user and password for your database.
Keep in mind that any change to config file requires a mongo restart
Related videos on Youtube
M.Yousefi
Updated on June 04, 2022Comments
-
M.Yousefi almost 2 years
A. I have a container that includes the following
1.NodeJS
version 8.11.4
2.Rocketchat
meteor appB. This is my
Dockerfile
FROM node:8.11.4 ADD . /app RUN npm install -g node-gyp RUN set -x \ && cd /app/programs/server/ \ && npm install \ && npm cache clear --force WORKDIR /app/ ENV PORT=3000 \ ROOT_URL=http://localhost:3000 EXPOSE 3000 CMD ["node", "main.js"]
C. This command is executed well
docker build -t memo:1.0 .
When I try to run the container, it encounters the following error in containers log
{"log":"MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]\n","stream":"stderr","time":"2019-01-24T21:56:42.222722362Z"}
So container can not be executed. The
mongodb
is running and I've added 0.0.0.0 tobindIp
in themongod.conf
file.# network interfaces net: port: 27017 bindIp: 127.0.0.1,0.0.0.0 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
My
mongodb
is installed in host(outside the container)
The problem was not resolved and my container status is ExitedI put the IP instead of the localhost,but it encounters the following error
{"log":"MongoNetworkError: failed to connect to server [192.168.0.198:27017] on first connect [MongoNetworkError: connect EHOSTUNREACH
-
M.Yousefi over 5 yearsI tried to connect with my host's IP, but not working. this is my docker run..
docker run --name memo -p 3000:3000 --env MONGO_URL=mongodb://192.168.0.198:27017/rocketchat --env MONGO_OPLOG_URL=mongodb://192.168.0.198:27017/local -d memo:1.0
-
twoTimesAgnew over 5 yearstry adding
--net=host
to your run command -
Vallie almost 4 yearsAfter researching a lot I found this and this really works. Thanks!!