1

Is it possible to connect to a docker container running a MongoDB image from an external nodejs application running locally? I've tried connecting via localhost:27017. Here's the docker compose file I'm using:

version: '3'
services:
  mongodb:
    image: 'bitnami/mongodb:3.6.8'
    ports:
      - "27017:27017"
    environment:
      - MONGODB_ROOT_PASSWORD=$MONGODB_ROOT_PASSWORD
      - MONGODB_USERNAME=$MONGODB_USERNAME
      - MONGODB_PASSWORD=$MONGODB_PASSWORD
      - MONGODB_DATABASE=$MONGODB_DATABASE
    volumes:
      - /data/db:/bitnami

I try connecting to it with the following url with no luck:

mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@localhost:27017

EDIT: Connecting via mongodb://localhost:27017 works, but the authentication url errors out. I printed out the result of this string and there's nothing particularly wrong with it. I verified that the username and password match the users inside mongo in the docker container.

app.listen(port, () => {
  console.log(`Example app listening on port ${port}!`);
  const url = (() => {
    if(process.env.MONGODB_USERNAME && process.env.MONGODB_PASSWORD) {
      return `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@localhost:27017/`;
    }
    console.log('could not find environment vars for mongodb');
  })();

  MongoClient.connect(url, (err, client) => {
    if(err) {
      console.log('DB connection error');
    } else {
      console.log("Connected successfully to server");
      client.close();
    }
  });
});
kag359six
  • 1,693
  • 2
  • 16
  • 21

3 Answers3

1

If the external nodejs application is also running in a docker container then you need to link the containers. Here is an example of a docker run cmd that links containers. I added environment variables to illustrate what host name and port you would use from inside the container.

    docker run -d -it -e DEST_PORT=27017 -e DEST_HOST='mongodb' --link mongodb external-application:latest
Fred
  • 152
  • 5
  • (You don't need `--link` these days; launching both containers from the same `docker-compose.yml` is enough to make the database reachable as the name `mongodb`, its key in the YAML file.) – David Maze Sep 25 '18 at 23:34
  • That’s correct, but I only see one container in the docket-compose.yml file. It was also said that the connection was trying to be made to localhost:27017 by an external application that’s also running locally. Which implies they are decoupled even though they are running on the same machine. So I wondered if maybe the person set up the “external application” in way specific to his or her intended use case but consequently prevented them to reach other by using localhost – Fred Sep 26 '18 at 01:12
  • Thanks for the feedback. I apologize for not specifying that the external web application is actually not living in another docker container. It resides on the host machine. I updated my question to include that information. – kag359six Sep 26 '18 at 10:23
  • What is the error you get when you try to connect to the mongodb container from your application? Also... Have you tried going into the container and verifying that everything is set up and running as you intended? – Fred Sep 26 '18 at 13:58
  • Yeah I verified everything. I updated my answer with my recent findings. – kag359six Sep 27 '18 at 21:28
  • In your original post you showed the url as `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@localhost:27017` with `mongodb://` then in your update you show `mongodb:${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@localhost:27017` with `mongodb:` without the `//` is it like that in the code? – Fred Sep 28 '18 at 14:18
  • @Fred I think that was just an error copying it over. The `//` is included in the code. Sorry about that. I corrected it in my question. – kag359six Sep 30 '18 at 15:38
  • Unable to connect to MongoDB from inside the docker. Any help on this? https://stackoverflow.com/questions/66022448/how-to-load-data-in-mongodb-running-in-host-from-inside-a-docker-running-on-the – Aakash Basu Feb 03 '21 at 07:06
1

It's important to always check the result of docker logs <container-name> --tail 25 -f. From my point of view, I think it is an issue related to permissions on this directory '/bitnami/mongodb'. Check out sameersbn comment how to fix this permission issue.

I'll assume it's the compose specification then. Try the following configuration

 environment:
   MONGODB_ROOT_PASSWORD:$MONGODB_ROOT_PASSWORD
   MONGODB_USERNAME:$MONGODB_USERNAME
   MONGODB_PASSWORD:$MONGODB_PASSWORD
   MONGODB_DATABASE:$MONGODB_DATABASE
 volumes:
   - '/data/db:/data/db'
Akongnwi Devert
  • 1,177
  • 12
  • 10
  • Thanks for the reply. The logs show that the docker container is listening for DB connections on port 27017 with no kinds of errors or warnings – kag359six Sep 26 '18 at 10:27
  • Ok. So what message do you get when you try to connect to the database in the container? – Akongnwi Devert Sep 26 '18 at 12:03
  • I wasn't getting a message, so I assumed it was an issue with the url I was using. I managed to get the connection successfully once I got rid of the extra credential paremeters in the mongodb url and left it as mongodb://localhost:27017. I assume the bitnami credentials aren't getting setup right, otherwise I don't see why I'd be able to connect to the DB without authorization. – kag359six Sep 26 '18 at 13:14
  • Let me correct that. Bitnami set up the credentials properly, but I can't connect to the db as one of the admin users created when the container was composed – kag359six Sep 26 '18 at 13:23
  • I'll assume it's the compose specification then. Try the following configuration environment: MONGODB_ROOT_PASSWORD:$MONGODB_ROOT_PASSWORD MONGODB_USERNAME:$MONGODB_USERNAME MONGODB_PASSWORD:$MONGODB_PASSWORD MONGODB_DATABASE:$MONGODB_DATABASE volumes: - '/data/db:/data/db' – Akongnwi Devert Sep 26 '18 at 15:39
  • Update: The configuration works as specified. I checked the mongo users in the container and they are all configured correctly. In fact, I even managed to connect to the DB from nodejs but only through localhost:27017 with no credentials passed. When I use the mongo authentication URL, nothing happens and nodejs gets a connection error. I'll update my answer with more relevant code. – kag359six Sep 27 '18 at 10:44
1

The issue turned out to be that I had changed the password in MONGODB_PASSWORD (it had an @ in it so I thought it would have interfered with the string parsing, so I consequently changed it). The problem is, when the container restarts it references the same volume (as it should), so the users were never updated and as a result I was logging in with the wrong credentials.

kag359six
  • 1,693
  • 2
  • 16
  • 21