Kubernetes Pod定义中的IP变量扩展

时间:2015-10-21 13:32:13

标签: docker kubernetes

我有一个docker镜像,需要命令行传递容器IP地址(或主机名)。

是否可以在容器命令定义中扩展pod主机名或IP?如果没有,在kuberneted部署容器中获取它的更好方法是什么?

在AWS中,我通常通过联系EC2元数据服务获取它,我可以做一些类似的联系kubernetes api,只要我能获得pod名称/ id?

感谢。

2 个答案:

答案 0 :(得分:2)

根据您的广告连播设置,您可以使用hostname -i

E.g。

$ kubectl exec ${POD_NAME} hostname -i
10.245.2.109

来自man hostname

...
-i, --ip-address
      Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.

-I, --all-ip-addresses
      Display  all  network  addresses  of  the  host. This option enumerates all configured addresses on all network interfaces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this
          option does not depend on name resolution. Do not make any assumptions about the order of the output.
...

答案 1 :(得分:1)

在v1.1(即将发布)中,您可以通过downward api将广告连播的IP作为环境变量公开(请注意published documentation适用于v1.0而不是&#39 ; t在向下的API中包含pod IP。

在v1.1之前,获得此功能的最佳方法可能是从pod中查询API。有关如何访问API的信息,请参阅Accessing the API from a Pod。广告连播名称是您的$HOSTNAME,您可以通过以下内容找到IP:

wget -O - ${KUBERNETES_RO_SERVICE_HOST}:${KUBERNETES_RO_SERVICE_PORT}/api/v1/namespaces/default/pods/${HOSTNAME} | grep podIP

虽然我建议您使用json解析器,例如jq

编辑:

只是想添加pod重启后不会保留IP,这就是为什么通常的建议是设置指向你的pod的服务。如果您确实使用了服务,则服务IP将被修复并充当容器的代理,即使在重新启动时也是如此。服务IP以environment variables提供,例如FOO_SERVICE_HOSTFOO_SERVICE_PORT