创建新容器后,是否可以运行命令从主机获取容器的IP地址?

基本上,一旦Docker创建了容器,我就想滚动我自己的代码部署和容器配置脚本。


当前回答

如果您需要一个特定的方便别名来获取特定的容器ip,请使用此别名,并提供公认的答案

alias dockerip='f(){ docker inspect $1|grep -i "ipaddress.*[12]*\.[0-9]*"|sed -e "s/^  *//g" -e "s/[\",]//g" -e "s/[*,]//g" -e "s/[a-zA-Z: ]//g" | sort --unique;  unset -f f; }; f'

然后你可以用

dockerip <containername>  

您也可以使用contained而不是containername

BTW接受了很好的答案,但没有产生干净的输出,所以我编辑了它,并这样使用;

alias dockerips='for NAME in $(docker ps --format {{.Names}}); do echo -n "$NAME:"; docker inspect $NAME|grep -i "ipaddress.*[12]*\.[0-9]*"|sed -e "s/^  *//g" -e "s/[\",]//g" -e "s/[_=*,]//g" -e "s/[a-zA-Z: ]//g "| sort --unique;done'

其他回答

Use:

docker inspect $CID | grep IPAddress | grep -v null| cut -d '"' -f 4 | head -1

对于窗口10:

docker inspect --format "{{ .NetworkSettings.IPAddress }}"  containerId

对于那些从谷歌来寻找从终端执行命令的解决方案(而不是通过脚本)的人来说,“jid”是一个交互式JSON向下钻取实用程序,具有自动完成和建议功能,它可以让你用更少的键入来做同样的事。

docker inspect $CID | jid

键入Tab.Net Tab,您将看到类似的内容:

[Filter]> .[0].NetworkSettings
{
  "Bridge": "",
  "EndpointID": "b69eb8bd4f11d8b172c82f21ab2e501fe532e4997fc007ed1a997750396355d5",
  "Gateway": "172.17.0.1",
  "GlobalIPv6Address": "",
  "GlobalIPv6PrefixLen": 0,
  "HairpinMode": false,
  "IPAddress": "172.17.0.2",
  "IPPrefixLen": 16,
  "IPv6Gateway": "",
  "LinkLocalIPv6Address": "",
  "LinkLocalIPv6PrefixLen": 0,
  "MacAddress": "02:42:ac:11:00:02",
  "Networks": {
    "bridge": {
      "Aliases": null,
      "EndpointID": "b69eb8bd4f11d8b172c82f21ab2e501fe532e4997fc007ed1a997750396355d5",
      "Gateway": "172.17.0.1",
      "GlobalIPv6Address": "",

键入.IPA选项卡,您将看到类似的内容:

[Filter]> .[0].NetworkSettings.IPAddress
"172.17.0.2"

仅为完整起见:

我真的很喜欢--format选项,但一开始我不知道它,所以我使用了一个简单的Python单行程序来获得相同的结果:

docker inspect <CONTAINER> |python -c 'import json,sys;obj=json.load(sys.stdin);print obj[0]["NetworkSettings"]["IPAddress"]'

为了扩展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'