How can I ping other containers in a docker network through their hostname?

前端 未结 3 1175
误落风尘
误落风尘 2021-02-19 10:47

I have a simple docker-compose set up as follows.

version: \"3\"
services:
  main:
    image: python:3.5.2
    entrypoint: /usr/bin/yes
    network_mode: bridge
         


        
相关标签:
3条回答
  • 2021-02-19 11:08

    Credits to tgogos: I just had to use the non-default bridge.

    For completeness, here is my working config.

    version: "3"
    services:
      main:
        networks:
          test:
        image: python:3.5.2
        entrypoint: /usr/bin/yes
    
      another:
        networks:
          test:
        image: python:3.5.2
        entrypoint: /usr/bin/yes
    
    
    networks:
      test:
        driver: bridge
    

    And the ping now works.

    $ docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    faa9f96d46a9        python:3.5.2        "/usr/bin/yes"      9 seconds ago       Up 9 seconds                            dockerplayground_main_1
    5b2d56ac0cd7        python:3.5.2        "/usr/bin/yes"      9 seconds ago       Up 8 seconds                            dockerplayground_another_1
    $ docker exec -it faa ping another
    PING another (172.18.0.2): 56 data bytes
    64 bytes from 172.18.0.2: icmp_seq=0 ttl=64 time=0.054 ms
    64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.047 ms
    64 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.059 ms
    64 bytes from 172.18.0.2: icmp_seq=3 ttl=64 time=0.066 ms
    
    0 讨论(0)
  • 2021-02-19 11:25

    Another solution I tried and worked was explicitly linking the containing you want to ping with host name. For example, I have a postgres container, and a server wants to connect to it.

    Run the server with the following

    docker run --name server --link postgres someserver:latest
    

    In the server container environment, you can then ping with (given postgres is on the same bridge/network and is running)

    ping postgres 
    

    Since --link has been deprecated, it is recommended to use network bridge.

    docker network create YOURNETWORK
    docker run --name postgres --network='YOURNETWORK' postgres:latest
    docker run --name server --network='YOURNETWORK' server:latest
    

    then the two containers can ping each other by name.

    0 讨论(0)
  • 2021-02-19 11:30

    delete this network_mode: bridge from your compose file, worked for me =).

    0 讨论(0)
提交回复
热议问题