How to get a Docker container's IP address from the host

后端 未结 30 2387
小鲜肉
小鲜肉 2020-11-22 08:45

Is there a command I can run to get the container\'s IP address right from the host after a new container is created?

Basically, once Docker creates the container, I

相关标签:
30条回答
  • 2020-11-22 09:29

    Based on some of the answers I loved, I decided to merge them to a function to get all the IP addresses and another for an specific container. They are now in my .bashrc file.

    docker-ips() {
        docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
    }
    
    docker-ip() {
      docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@"
    }
    

    The first command gives the IP address of all the containers and the second a specific container's IP address.

    docker-ips
    docker-ip YOUR_CONTAINER_ID
    
    0 讨论(0)
  • 2020-11-22 09:29

    Just for completeness:

    I really like the --format option, but at first I wasn't aware of it so I used a simple Python one-liner to get the same result:

    docker inspect <CONTAINER> |python -c 'import json,sys;obj=json.load(sys.stdin);print obj[0]["NetworkSettings"]["IPAddress"]'
    
    0 讨论(0)
  • 2020-11-22 09:31

    To get all container names and their IP addresses in just one single command.

    docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}' $(docker ps -aq)
    

    If you are using docker-compose the command will be this:

    docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
    

    The output will be:

    /containerA - 172.17.0.4
    /containerB - 172.17.0.3
    /containerC - 172.17.0.2
    
    0 讨论(0)
  • 2020-11-22 09:31

    In Docker 1.3+, you can also check it using:

    Enter the running Docker (Linux):

    docker exec [container-id or container-name] cat /etc/hosts
    172.17.0.26 d8bc98fa4088
    127.0.0.1   localhost
    ::1 localhost ip6-localhost ip6-loopback
    fe00::0 ip6-localnet
    ff00::0 ip6-mcastprefix
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    172.17.0.17 mysql
    

    For windows:

    docker exec [container-id or container-name] ipconfig
    
    0 讨论(0)
  • 2020-11-22 09:31

    Combining previous answers with finding the container ID based on the Docker image name:

    docker inspect --format '{{ .NetworkSettings.IPAddress }}' `docker ps | grep $IMAGE_NAME | sed 's/\|/ /' | awk '{print $1}'`
    
    0 讨论(0)
  • 2020-11-22 09:32

    You can use docker inspect <container id>.

    For example:

    CID=$(docker run -d -p 4321 base nc -lk 4321);
    docker inspect $CID
    
    0 讨论(0)
提交回复
热议问题