Mongo-express "Could not connect to database using connectionString"

78 views Asked by At

I'm getting the error:

mongo-express_1 | Could not connect to database using connectionString: mongodb://root:1234@mongo:27017/"

while running docker-compose up.

docker-compose:

version: '3.9'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "5000:5000"
    depends_on:
      - mongodb
      - nginx

  nginx:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro

  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=1234
      - MONGO_INITDB_DATABASE=mydatabase
    volumes:
      - mongodb_data:/data/db

  mongo-express:
    image: mongo-express
    restart:  always  
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: 1234        
      ME_CONFIG_MONGODB_SERVER: mongo
      ME_CONFIG_MONGODB_PORT: 27017         
    depends_on:
      - mongodb
    ports:
      - 8081:8081

volumes:
  mongodb_data:

does anyone know how to solve this?

1

There are 1 answers

0
milanbalazs On

The ME_CONFIG_MONGODB_SERVER variable in mongo-express service is not set correctly. It should be ME_CONFIG_MONGODB_SERVER=mongodb because the MongoDB service's name is mongodb (It's used as hostname inside a Docker network).

If you still get error, then I suggest to define/use a docker network for the services. Just like:

version: '3.9'

services:
  ...
  ...

  mongodb:
    image: mongo:latest
    # It's not needed to open if you want to access it only from mongo-express service.
    # The services are able to communicate via any port inside the same Docker network.
    ports:
      - "27017:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=1234
      - MONGO_INITDB_DATABASE=mydatabase
    volumes:
      - mongodb_data:/data/db
    networks:
      - mongo-net

  mongo-express:
    image: mongo-express
    restart:  always  
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: 1234
      # This variable is the problematic point is your question.
      # It has to be changed from "mongo" to "mongodb"
      ME_CONFIG_MONGODB_SERVER: mongodb
      ME_CONFIG_MONGODB_PORT: 27017
    depends_on:
      - mongodb
    ports:
      - 8081:8081
    networks:
      - mongo-net

volumes:
  mongodb_data:

networks:
  mongo-net: {}