简体   繁体   中英

How to get two Docker containers talking to each other?

I've got two Docker containers running. One is MongoDB and one is a container running a simple rest API that should be able to query the MongoDB container.

Port mappings

  • 0.0.0.0:28001->27017/tcp (mongodb)
  • 0.0.0.0:3000->3000/tcp (restapi)

Commands used for the MongoDB image

docker run -p 28001:27017 -v /home/ubuntu/docker/mongodb/mongod.conf:/etc/mongod.conf --name mongodb_container -d mongodb_image

I override mongo.conf to add 0.0.0.0 to bind IP

net:
  port: 27017
  bindIp: [127.0.0.1,0.0.0.0]

Run command used for the API:

docker container run -it -v /home/ubuntu/docker/node_modules:/usr/lib/node_modules -p 3000:3000 --name rest_container rest_image /bin/bash

I'm able to query the rest api, but it hangs and times out (never returns result). The rest config file looks something like this:

{ "db": {
  'port': 28001,
  'host': "192.168.123.191"
  },
  'server': {
    'port': 3000,
        'timeout': 120,
    'address': "0.0.0.0"
  },
  'flavor': "regular",
  'debug': true
};

Internal IP of the rest api container:

172.17.0.4

Internal IP of the mongodb container:

172.17.0.2

I know the API works because I'm able to do queries without running the programs on docker. Ports 27017 and 3000 are both exposed in the Dockerfile. In the mongodb container I can also see that the number of connections increases every time I do a query.

Prior to docker 1.9 you had to use "a link" but it has been deprecated. Now you should create a "custom network" https://docs.docker.com/engine/userguide/networking ) and run your containers within this network.

For example :

docker network create --driver bridge my_network

docker run  --network=my_network -p 28001:27017 -v /home/ubuntu/docker/mongodb/mongod.conf:/etc/mongod.conf --name mongodb_container -d mongodb_image

docker container run  --network=my_network -it -v /home/ubuntu/docker/node_modules:/usr/lib/node_modules -p 3000:3000 --name rest_container rest_image /bin/bash

And you need to configure Node to talk with Mongo using a hostname (which is the same as the name of containe'rs) and using the port of the Mongo container and not the external one, I mean port 27017 not 28001. That's why port binding -p 28001: 27017 is unnecessary unless you want to access it from the outside.

{ "db": {
  'port': 27017,
  'host': "mongodb_container"
  },
  'server': {
    'port': 3000,
    'timeout': 120,
    'address': "0.0.0.0"
  },
  'flavor': "regular",
  'debug': true
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM