To retrieve the IP address of a Docker container from the host, several methods can be used, with the most common being the docker inspect command and the docker network inspect command.
Using the docker inspect Command
- Locate the Container ID or Name
First, identify the container ID or name you want to query. You can view all running containers and their IDs and names using the docker ps command.
bashdocker ps
- Query the Container's IP Address
Use the docker inspect command with the --format filter parameter to directly retrieve the container's IP address. For example:
bashdocker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id_or_name
This command outputs the IP address of the container within the network it is connected to.
Using the docker network inspect Command
- Determine the Network the Container is Connected To
If you know the network the container is connected to, you can directly use the docker network inspect command to view detailed information about all containers in that network. First, use the docker network ls command to view all networks:
bashdocker network ls
- View Network Details
Then, use the docker network inspect command to view detailed information about the specific network, which includes all containers connected to it and their IP addresses:
bashdocker network inspect network_name_or_id
Practical Application Example
Suppose I have a container named web-app in my development environment, and I need to query its IP address for network connectivity testing. I will use the following steps:
- Find the Container ID:
bashdocker ps
- Retrieve the IP Address:
bashdocker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web-app
This will provide the IP address of the web-app container for subsequent testing or development work.
By using the above methods, we can effectively retrieve the IP address of a Docker container, which is very useful for network configuration, service deployment, and troubleshooting in various scenarios.