Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect to MongoDB container from other Docker container

Tags:

docker

mongodb

I have two containers linked together by Docker compose and I can successfully ping the container containing MongoDB from the one containing my node.js app using the hostname. However, when it comes to actually connecting to the database, node.js tells me the connection is refused. I am using Docker for Mac if that helps.


    mongoose.connect("mongodb://mongo", {server: {auto_reconnect: true}}).catch(error => {
            console.log("DB CONNECTION ERROR");
            console.log(error)
        });


Here is my docker-compose.yml file:

    version: "3"

    services:
      mongo:
        image: mongo:latest
        volumes:
          - ./db:/data/db
        restart: always
        expose:
          - 27017
        ports:
          - 27017:27017
        container_name: mongo

      goose:
        depends_on:
          - mongo
        build: .
        volumes:
          - ./app/server/templates:/usr/src/app/app/server/templates
        expose:
          - 3005
        restart: always
        ports:
          - 3005:3005
        container_name: goose-compose

like image 490
jamestheasiangenius Avatar asked Dec 02 '25 13:12

jamestheasiangenius


1 Answers

Use this as your reference,

Dockerfile

FROM node:alpine
RUN mkdir -p /usr/src/app  # -p create all parent folders
WORKDIR /usr/src/app
COPY package.json ./
COPY package-lock.json ./
RUN npm install
COPY . .

docker-compose.yml

version: "3.8"

services:
  web:
    image: docker-node-mongo
    container_name: docker-node-mongo
    build: .  # path to your Dockerfile
    command: nodemon src/app.js # Use nodemon to reload on changes
    restart: always
    volumes:
      - ./src:/usr/src/app # To enable auto reload on changes
    ports:
      - "4000:4000"
    depends_on:
      - mongo_db

  mongo_db:
    image: mongo
    restart: always
    container_name: mongo_container # Use this in the connection url
    command: mongod -port 27017 --dbpath /data/db --replSet rs0
    ports:
      - "27017:27017"
    volumes:
      - mongo_storage:/data/db

volumes:
  mongo_storage:

Connection file

 const mongoose = require("mongoose")
 mongoose.connect("mongodb://mongo_container:27017/mongo-test?replicaSet=rs0", {
    useNewUrlParser: true,
    useCreateIndex: true,
 })

To enable replica set in mongodb,

docker compose up --build -d # to build your app in docker

docker exec -it mongo_db mongo # to enter in the mongo shell in docker

rs.initiate({ _id: "rs0", version: 1, members: [{ _id: 0, host : "mongo_db:27017" }] })

like image 155
Alish Giri Avatar answered Dec 04 '25 07:12

Alish Giri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!