maks
maks

Reputation: 6006

Can't connect to mongodb in docker container from local machine

I have running docker container with mongodb on it someId mongo:3.6 "docker-entrypoint.s…" 11 days ago Up 11 days 0.0.0.0:27017->27017/tcp myMongo When I try to connect to that mongo from local machine via mongo localhost:27017 I get en error

error: couldn't connect to server localhost:27017, connection attempt failed: SocketException: Error connecting to localhost:27017 (127.0.0.1:27017) :: caused by :: Connection refused : connect@src/mongo/shell/mongo.js:328:13

What I'm doing wrong?

Update Here is an output from docker-compose ps

myMongo docker-entrypoint.sh --wir ... Up 0.0.0.0:27017->27017/tcp

Docker-compose file

version: '2'

services:
  mongo:
    image: "mongo:3.6"
    container_name: myMongo
    ports:
     - "27017:27017"
    mem_limit: 2G

Update final Restarted my ubuntu, started the docker-compose once agin and all started to work as expected: mongo localhost now works. Suspect that there is a problem in ubuntu 18.04 logout process, because before that(and before system restart) I preformed logout/login several times

Upvotes: 1

Views: 5039

Answers (1)

krishna Prasad
krishna Prasad

Reputation: 3812

Steps to start docker mongo containers and connect from local system:

  1. Create docker docker-compose.yml file as :

    version: '2'
    services:
      mongo:
        image: "mongo:3.6"
        container_name: myMongo
        ports:
         - "27017:27017"
        mem_limit: 2G
    
  2. Before making docker composer up, you should check that port 27017 is already occupied by some other processes or not as:

    netstat -an | grep 27017
    

    or

    lsof -i -P ;// look for the port 27017
    

    If port number 27017 is already occupied then you have to change the port number in the docker compose from 27027 to whatever you want to be.

  3. start the docker container by below command [you have to be on the same directory wherever docker-compose.yml file is]

    docker-compose up
    

    check the below screenshot how the containers created and started enter image description here

  4. Now your docker container with mongo db 3.6 is up and running, open new terminal and connect with mongo shell as mongo if the default port is 27017 otherwise mongo --port <whateverport number in docker compose>

Hope this explanation help to you as well as someone else also :)

Upvotes: 1

Related Questions