Advertisement
Advertisement


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


Question

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 want to roll my own code deployment and container configuration scripts.

2019/12/19
1
1485
12/19/2019 11:50:40 PM

Accepted Answer

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.

2019/12/19
2475
12/19/2019 11:51:24 PM

You can use docker inspect <container id>.

For example:

CID=$(docker run -d -p 4321 base nc -lk 4321);
docker inspect $CID
2019/12/19

First get the container ID:

docker ps

(First column is for container ID)

Use the container ID to run:

docker inspect <container ID>

At the bottom,under "NetworkSettings", you can find "IPAddress"

Or Just do:

docker inspect <container id> | grep "IPAddress"
2018/05/09

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"
2019/12/20

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
2017/03/11

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

docker-ip() {
  docker inspect --format '{{ .NetworkSettings.IPAddress }}' "[email protected]"
}

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}}' "[email protected]"
}
2017/03/11