如何从主机获取Docker容器的IP地址?
Is there a command I can run to get the container's IP address right from the host after a new cont
本文翻译自:How to get a Docker container's IP address from the host?
Is there a command I can run to get the container's IP address right from the host after a new container is created? 创建新容器后,是否可以运行命令以从主机获取容器的IP地址?
Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts. 基本上,一旦Docker创建了容器,我想滚动自己的代码部署和容器配置脚本。
#1楼
参考:https://stackoom.com/question/19zVR/如何从主机获取Docker容器的IP地址
#2楼
You can use docker inspect <container id>
您可以使用docker inspect <container id>
Example: 例:
CID=$(docker run -d -p 4321 base nc -lk 4321);
docker inspect $CID
#3楼
The --format
option of inspect comes to the rescue. inspect的--format
选项可以解决。
Modern Docker client syntax: 现代Docker客户端语法:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
Old Docker client syntax: 旧的Docker客户端语法:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
These commands will return the Docker container's IP address. 这些命令将返回Docker容器的IP地址。
As mentioned in the comments: if you are on Windows , use double quotes "
instead of single quotes '
around the curly braces. 如注释中所述:如果您使用的是Windows ,请在大括号周围使用双引号"
而不是单引号'
。
#4楼
In Docker 1.3+, you can also check it via steps below: 在Docker 1.3+中,您还可以通过以下步骤进行检查:
Enter the running Docker (Linux): 输入正在运行的Docker(Linux):
docker exec [container-id or container-name] cat /etc/hosts
172.17.0.26 d8bc98fa4088
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.17 mysql
For windows: 对于Windows:
docker exec [container-id or container-name] ipconfig
#5楼
Add this shell script in your ~/.bashrc
or relevant file: 将此shell脚本添加到~/.bashrc
或相关文件中:
docker-ip() {
docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$@"
}
Then, to get an IP address of a container, simply do this: 然后,要获取容器的IP地址,只需执行以下操作:
docker-ip YOUR_CONTAINER_ID
For the new version of the Docker, please use the following: 对于新版本的Docker,请使用以下命令:
docker-ip() {
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@"
}
#6楼
为了扩展ko-dos的答案,下面是一个别名,用于列出所有容器名称及其IP地址:
alias docker-ips='docker ps | tail -n +2 | while read -a a; do name=${a[$((${#a[@]}-1))]}; echo -ne "$name\t"; docker inspect $name | grep IPAddress | cut -d \" -f 4; done'
更多推荐
所有评论(0)