MongoDB Docker – How to Connect Backend to MongoDB Docker Container

connectionmongodb

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.

Best Answer

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"