Search code examples
node.jsmongodbdockerdocker-composedocker-swarm

Connect nodejs App in one docker container to mongodb in another on Docker Swarm


I have setup a docker stack (see docker-compose.yml) below.

It has 2 Services: - A nodejs (loopback) service running in one (or more) containers. - A mongodb running in another container.

What HOST do I use in my node application to allow it to connect to the mongodb in another container (currently on same node, but could be on different node if I setup a swarm).

I have tried bridge, webnet, hosts IP etc.. but no luck.

Note: I am passing the host into the nodejs app with environment variable "MONGODB_SERVICE_SERVICE_HOST".

Thanks in advance!!

version: "3"
services:
  web:
    image: myaccount/loopback-app:latest
    deploy:
      replicas: 2
      restart_policy:
        condition: on-failure
    ports:
      - "8060:3000"
    environment:
        MONGODB_SERVICE_SERVICE_HOST: "webnet"
    depends_on:
      - mongo
    networks:
      - webnet
  mongo-database:
    image: mongo
    ports:
      - "27017:27017"
    volumes:
      - "/Users/jason/workspace/mongodb/db:/data/db"
    deploy:
      placement:
        constraints: [node.role == manager]
    networks:
      - webnet
networks:
  webnet:

Solution

  • webnet is not the host. This is mongo-database.
    So change webnet to mongo-database.

    ENV MONGO_URL "mongodb://containerName:27017/dbName" 
    

    To check mongo-database communication, enter into the nodejs container, and try to ping mongo-database :

    ping mongo-database 
    

    If it works, you know that your server can communicate with your mongo instance.