Blog

How do I get a Docker Container IP Address from the Host?

docker-container-basic
Docker

How do I get a Docker Container IP Address from the Host?

To retrieve the IP address of a Docker container from the host machine, you can use the Docker command-line interface (CLI) along with some filtering and formatting options. Lets see how you can do it:

Method 1: Using docker inspect command:

To get detailed information about the container you can use the docker inspect command along with the container name or ID . To bring out just the IP address, you can use the –format option to specify a Go template that pluck out the IP address from the container’s network configuration.

  1. Open a terminal on the host machine.
  2. Run the following command:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_name_or_id>

Replace with the actual name or ID of the Docker container.

For example, if you have a container named “myworld” you would run:

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

This command will output the IP address of the myworld container.

Method 2: Using docker exec and ifconfig (Linux containers):

  1. Open a terminal on the host machine.
  2. Run the following command, replacing container_name_or_id with the actual name or ID of your Docker container.
docker exec container_name_or_id ifconfig

Look for the IP address under the network interface associated with the container.

Method 3: Using docker inspect and jq (if installed):

  1. Open a terminal on the host machine.

2. Install jq if you haven’t already (a tool for parsing JSON data):

sudo apt-get install jq  # For Debian/Ubuntu

3. Run the following command, replacing container_name_or_id with the actual name or ID of your Docker container:

docker inspect container_name_or_id | jq -r '.[0].NetworkSettings.Networks.bridge.IPAddress'

This will output the IP address of the specified container.

In both cases, the command will output the IP address of the specified Docker container. Make sure the container is running when you execute this command, otherwise, you might not get a valid IP address.

Remember that Docker container IPs can change upon container restarts or recreation. If you need a more persistent way to access the container, consider setting up a bridge network or using Docker Compose to manage your containers.

Spread the love

Leave your thought here

Your email address will not be published. Required fields are marked *