Docker
Published in Docker
avatar
3 minutes read

Getting a Docker container's IP address from the host

Getting a Docker container's IP address from the host

To obtain a Docker container's IP address from the host machine, you can use Docker commands and inspect the container's network settings.

Using docker inspect command

The docker inspect command provides detailed information about a container, including its network configuration.

# Syntax:
# docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_name_or_id>

# Example: Get the IP address of a running container
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my_running_container

Replace <container_name_or_id> with the name or ID of the container you want to inspect. The command will output the IP address of the container.

Using docker inspect with grep (alternative method)

You can use docker inspect in combination with grep to extract the IP address.

# Example: Get the IP address of a running container using grep
docker inspect my_running_container | grep -w "IPAddress" | awk '{print $2}' | tr -d ',"'

Replace my_running_container with the name or ID of your running container. This command filters the relevant line containing "IPAddress" and then uses awk and tr to extract only the IP address.

Using docker inspect with jq (if available)

If you have jq installed on your host machine, you can use it to parse the JSON output of docker inspect.

# Example: Get the IP address of a running container using jq
docker inspect my_running_container | jq -r '.[0].NetworkSettings.Networks[].IPAddress'

Replace my_running_container with the name or ID of your running container. The jq command filters the JSON output and extracts the IP address directly.

Note

  • If the container is not running, you may not get an IP address using the above methods. Make sure the container is running or use the appropriate command to start it (docker start <container_name_or_id>).
  • In cases where a container has multiple network interfaces or IP addresses, the methods mentioned above might return multiple IP addresses.

0 Comment