Search code examples
dockerubuntuhostnamedocker-network

How to access docker container through hostname?(from my host pc)


(I'm doing this just for practice, to know docker.)

My host PC is ubuntu 18.04 LTS.
And this is my docker-compose file(default network mode is bridge).

version: "2"
services:
  zookeeper1:
    image: wurstmeister/zookeeper
  zookeeper2:
    image: wurstmeister/zookeeper
  zookeeper3:
    image: wurstmeister/zookeeper

In docker container, they can find each other.

> docker container exec -it 8b1c2b412989 ping zookeeper2
PING zookeeper2 (172.19.0.3) 56(84) bytes of data.
64 bytes from setup-zookeeper-kafka_zookeeper2_1.setup-zookeeper-kafka_default (172.19.0.3): icmp_seq=1 ttl=64 time=0.097 ms
64 bytes from setup-zookeeper-kafka_zookeeper2_1.setup-zookeeper-kafka_default (172.19.0.3): icmp_seq=2 ttl=64 time=0.129 ms

But when I tried to my host PC, it doesn't work

> ping zookeeper2
ping: zookeeper2: Name or service not known

> ping 8b1c2b412989 # container id also doesn't work
ping: 8b1c2b412989: Name or service not known

Ping with ip, it works well.

> ping 172.19.0.3
PING 172.19.0.3 (172.19.0.3) 56(84) bytes of data.
64 bytes from 172.19.0.3: icmp_seq=1 ttl=64 time=0.142 ms
64 bytes from 172.19.0.3: icmp_seq=2 ttl=64 time=0.046 ms

I added hostname property, it still doesn't work.

version: "2"
services:
  zookeeper1:
    hostname: zookeeper1
    image: wurstmeister/zookeeper
  zookeeper2:
    hostname: zookeeper2
    image: wurstmeister/zookeeper
  zookeeper3:
    hostname: zookeeper3
    image: wurstmeister/zookeeper

How can I access container with hostname from my host PC?
Now, I only can do with ports options.(or I have to write static IP address)

What this I am thinking wrong?


Solution

  • This happens as Giga commented. If you don't have the hostname in your /etc/hosts there is no magic here.

    If you need to ping for healthcheck you can use docker-compose's healthcheck So, with it you can always look your zookeepers if they are alive or not.

    If you insist that you need to ping with hostname, I recommend roll up your sleeves, and make a bash script using docker format like ...

    docker ps --format "table {{.ID}}\t{{.Ports}}" 
    

    And then with every containerid with the container Name do:

    docker inspect <containerid> and extract the IP like you have [here.][2]