How to connect to mongodb using docker-compose?

You can do something like below:

version: '3'

services:
  mongo:
    image: 'mongo:3.4.1'
    ports:
      - '27017:27017'
    volumes:
      - 'mongo:/data/db'

  puma:
    tty: true
    stdin_open: true
    depends_on:
      - 'mongo'
    build:
      context: .
      dockerfile: Dockerfile.puma
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    ports:
      - '3000:3000'
    volumes:
      - '.:/app'
    environment:
      - SECRET_KEY_BASE=secret
      - MONGO_URL=mongodb://mongo:27017/app_development
volumes:
  mongo:

As you might have noticed, you can connect to mongo service running on mongo container from other containers located in the same docker-compose.yml file using the connection string like mongodb://mongo:27017.

In case you want to connect from the host, you can use mongodb://localhost:27017 if you have exposed mongo port as shown above.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)