Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker container cannot connect to localhost mongodb [duplicate]

A. I have a container that includes the following
1. NodeJS version 8.11.4
2. Rocketchat meteor app

B. 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 to bindIp in the mongod.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 Exited

I 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

like image 405
M.Yousefi Avatar asked Oct 21 '25 12:10

M.Yousefi


1 Answers

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.
like image 193
twoTimesAgnew Avatar answered Oct 23 '25 02:10

twoTimesAgnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!