When working with Docker containers on a Linux server, troubleshooting network connectivity issues is a common task. Whether you need to connect two containers manually, configure a reverse proxy like Nginx, or simply verify that your application is broadcasting on the correct subnet, you will frequently need to find the internal IP address assigned to a specific container.
Docker handles networking by creating virtual bridge networks and automatically assigning IP addresses to containers when they start. Here are the most effective ways to find a container’s IP address using the Linux terminal.
Method 1: Use the Docker Inspect Command
The docker inspect command provides a wealth of low-level information about Docker objects, including containers, in JSON format. While you can output the entire JSON block and scroll through it, it is much more efficient to use Go templates to extract exactly the data you need.
To find the IP address of a specific container, open your terminal and run the following command, replacing container_name_or_id with the actual name or ID of your container:
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
This command parses the JSON output and returns only the raw IP address, such as 172.17.0.2. This is highly useful if you need to pass the IP address directly into a bash script or another command.
Method 2: Inspect the Entire Docker Network
If you have multiple containers running on a specific custom Docker network and you want to see the IP addresses of all of them simultaneously, inspecting the network itself is often faster.
First, list your available Docker networks to find the name of the network you want to check:
docker network ls
Once you know the network name (for example, my_custom_network), run the following command:
docker network inspect my_custom_network
This will output a JSON block. Scroll down to the "Containers" section. Here, you will see a list of all containers currently attached to that network, alongside their MAC addresses and IPv4 addresses. This provides a helpful overview of the entire subnet topology without needing to query each container individually.
Important Considerations for Docker Networking
It is important to remember that by default, Docker assigns IP addresses dynamically. If a container stops and restarts, or if the host machine reboots, there is no guarantee that the container will retain the same IP address.
If you are relying on IP addresses for communication between containers, it is strongly recommended to use Docker’s built-in DNS resolution instead. By creating a custom user-defined bridge network and attaching your containers to it, you can simply use the container’s name as a hostname (e.g., http://database_container:3306), and Docker will automatically resolve it to the correct internal IP address, regardless of how often it changes.