简体   繁体   中英

access mongodb running inside docker + wsl2, on Host windows

I am running mongodb instance using docker-compose as docker container, which is running in a WSL2 environment on windows 10 machine.

在此处输入图片说明

From my host windows 10 machine, i am able to connect to nodejs container http://localhost:3001/api/v1 , also using mongo-compass I can't connect to mongodb instance,

The error I get is connect ECONNREFUSED 127.0.0.1:27017 .

Please help, how can i connect to mongodb instance from host windows machine.

If you want to connect from your host machine to one of the docker container's ports you need to make sure this port is exposed to the host.

From what I can see on your screenshot, your containers configured is such a way, that only node container exposes 3001 port, therefore you can reach it from your host via localhost.

The problem with mongo occurs because your docker-compose configuration doesn't expose mongodb container's (named mongo on your screenshot) port 27017 to the host machine.

So to fix that, you need to set ports . As an example:

...
services:
...
mongo:
  ...
  ports:
    - "27017"
...

Please note, you need to make sure 27017 are not used by any other service running on your host before exposing it. IF this port is busy and you don't want to stop the service, you can simply use another port on your host:

...
mongo:
  ...
  ports:
    - "27018:27017"
...

More about docker-compose configs is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM