Score:0

How to connect backend to a mongodb docker container

cn flag

I made this docker-compose file as written on docker hub / mongodb then I use the command docker-compose up -d which pretty standard to launch a container.

# Use root/example as user/password credentials
version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

bf4a595a508d   mongo-express   "tini -- /docker-ent…"   About an hour ago   Up About an hour   0.0.0.0:8081->8081/tcp, :::8081->8081/tcp   intake-app_mongo-express_1
b5fcc2d2386d   mongo           "docker-entrypoint.s…"   About an hour ago   Up About an hour   27017/tcp                                   intake-app_mongo_1

Now I'm trying to connect my backend to it.

With postresql it would be something like postgresql://root:example@localhost:8081/db_name

What would it be with mongo ?

PS: I can connect to the db in my web browser at http://localhost:8081 but I cannot connect to the db from the command line with mongo.

Michael Hampton avatar
cz flag
You've already got the correct connection string right there in your `docker-compose.yml`!
Score:1
cn flag

From the official docker hub page:

The MongoDB server in the image listens on the standard MongoDB port, 27017, so connecting via Docker networks will be the same as connecting to a remote mongod.

You don't state where you are connecting from and how. If it's another container then you can use the port directly otherwise you need to expose it first.

As for the connection string it's generally from the official docs:

mongo mongodb://$[hostlist]/$[database]?authSource=$[authSource] --username $[username]

You can also use the mongo-express container you used to get the details above or from the docker hub README. So in your case:

mongodb://root:example@mongo:27017/

If your client isn't in a docker container in the same stack you need to expose port 27017 from the first mongodb container:

ports:
    - "27017:27017"
Pierre Lovergne avatar
cn flag
I forgot to expose the port.. Thank you very much
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.