Ghadi Freiha
Ghadi Freiha

Reputation: 5

Docker modified node container not connecting or seeing mongo db container within docker swarm overlay network

I have a docker swarm service that uses mongodb, mongo-express and a custom node image. I have created a simple docker yaml file to launch them all together.

version: '3.1'

services:
  mongo:
    image: mongo:4.0.6-xenial
    environment:
      MONGO_INITDB_ROOT_USERNAME:
      MONGO_INITDB_ROOT_PASSWORD:

  mongo-express:
    image: mongo-express
    environment:
      MONGO_INITDB_ROOT_USERNAME:
      MONGO_INITDB_ROOT_PASSWORD:
    ports:
    - "8081:8081"

  backend:
    image: backend
    ports:
     - "2222:2222"

Now I know that docker swarm automatically creates a default overlay network among all the nodes. My docker inspect network displays all the containers within the network. I can see the backend connected using localhost:2222 and mongo-express using localhost:8081.

My problem is the backend is not connecting, nor can it even see the mongo database. I tried ssh-ing into the mongo-express container, pinged localhost:27017 successfuly, then pinged localhost:2222 successfuly.

However, trying to ping/curl mongo-express or mongodb from the backend container wields nothing, its like the ports arent even visible. (localhost:2222 works but localhost:8081 or localhost:27017 don't).

EDIT: I've ssh'd into the backend container again after copying mongo's ip address from docker inspect network, then were able to curl successfully 10.0.5.8:27017. Why isn't it on the localhost?

Upvotes: 1

Views: 310

Answers (1)

Thomasleveil
Thomasleveil

Reputation: 104055

Each container has it's own IP address. This implies that within a docker container, localhost refers to itself. This is why you cannot expect to reach the mongo container IP address from the mongo-express container using localhost.

Docker compose and swarm provide us with a convenient way to address containers by their service name as defined in the docker-compose.yml file.

So from the mongo-express container, connect to mongo using mongo:27017.

Upvotes: 2

Related Questions