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

后端 未结 30 2366
小鲜肉
小鲜肉 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:39

    To get the IP address and host port of a container:

    docker inspect containerId | awk '/IPAddress/ || /HostPort/'
    

    Output:

        "HostPort": "4200"
                        "HostPort": "4200"
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",
    
    0 讨论(0)
  • 2020-11-22 09:40

    Add this shell script in your ~/.bashrc or relevant file:

    docker-ip() {
      docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$@"
    }
    

    Then, to get an IP address of a container, simply do this:

    docker-ip YOUR_CONTAINER_ID
    

    For the new version of the Docker, please use the following:

    docker-ip() {
            docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@"
    }
    
    0 讨论(0)
  • 2020-11-22 09:40

    I use this simple way

    docker exec -it <container id or name> hostname -i
    

    e.g

    ubuntu@myhost:~$ docker exec -it 3d618ac670fe hostname -i
    10.0.1.5
    
    0 讨论(0)
  • 2020-11-22 09:42

    The --format option of inspect comes to the rescue.

    Modern Docker client syntax is:

    docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
    

    Old Docker client syntax is:

    docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
    

    These commands will return the Docker container's IP address.

    As mentioned in the comments: if you are on Windows, use double quotes " instead of single quotes ' around the curly braces.

    0 讨论(0)
  • 2020-11-22 09:42
    docker inspect CONTAINER_ID | grep "IPAddress"
    

    You can add -i to grep for ignoring the case then even the following will work:

    docker inspect CONTAINER_ID | grep -i "IPaDDreSS"
    
    0 讨论(0)
  • 2020-11-22 09:42
    docker inspect --format '{{ .NetworkSettings.IPAddress }}' <containername or containerID here>
    

    The above works if the container is deployed to the default bridge network.

    However, if using a custom bridge network or a overlay network, I found the below to work better:

    docker exec <containername or containerID here> /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
    
    0 讨论(0)
提交回复
热议问题