How to let different Docker containers talk to eac

2020-03-30 20:53发布

问题:

I needed to test my kafka consumer and message triggers in a controlled environment. So I made an ansible project for creating some mock kafka servers: mokafelk.

It works fine except the security is shit. The playbook spins up a 3-node dockerized kafka cluster by default but the listening ports on the kafka servers are exposed to all. Here's the jinja2 template of the Dockerfile used for creating the cluster.

Basically I want the containers to be able to talk to each other. I don't think container linking is an option because it seems to me linking is only one-way. But exposing a port using 127.0.0.1:{{ port }}:{{ port }} only exposes the port to the hosting machine and does not expose the port to the other containers if I am correct. 0.0.0.0:{{ port }}:{{ port }} exposes the port to the whole world. So how could I link two+ containers both ways? This must be a common problem but I don't seem to find a quick solution...

回答1:

The docker container networking is explained in detail here: https://docs.docker.com/engine/userguide/networking/dockernetworks/

In short:

By default docker daemon adds a network adapter docker0 to the host system (it tries to guess an available IP, often uses 172.17.0.1). You can see this in $ ifconfig.

All containers are by default connected to this network in incremental IPs. You can examine the containers network settings via $ docker inspect <container name>.

So chances are good your docker cluster's IPs are as follows:
kafka1 172.17.0.2
kafka2 172.17.0.3
kafka3 172.17.0.4
elasticsearch 172.17.0.5
kibana 172.17.0.6

You can then access your kafkas at 172.17.0.2:9092, 172.17.0.3:9092, 172.17.0.4:9092 from the host system and from the containers alike.