乐闻世界logo
搜索文章和话题

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

1个答案

1

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

  1. 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.

bash
docker ps
  1. 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:

bash
docker 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

  1. 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:

bash
docker network ls
  1. 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:

bash
docker 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:

  1. Find the Container ID:
bash
docker ps
  1. Retrieve the IP Address:
bash
docker 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.

2024年8月10日 00:25 回复

你的答案