I have a docker image that needs the container IP address (or hostname) to be passed by the command line.
Is it possible expansion the pod hostname or IP in the container command definition? if not, what is the better way to obtain it in a kuberneted deployed container?
In AWS I usually obtain it by contacting the EC2 meta-data service, I can do somethng similar contacting the kubernetes api, as long as I can obtain the pod name/id?
Thanks.
Depending on your pod setup, you may be able to use hostname -i
.
E.g.
$ kubectl exec ${POD_NAME} hostname -i
10.245.2.109
From 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.
...
In v1.1 (releasing soon) you can expose the pod's IP as an environment variable through the downward api (note that the published documentation is for v1.0 which doesn't include pod IP in the downward API).
Prior to v1.1, the best way to get this is probably by querying the API from the pod. See Accessing the API from a Pod for how to access the API. The pod name is your $HOSTNAME
, and you can find the IP with something like:
wget -O - ${KUBERNETES_RO_SERVICE_HOST}:${KUBERNETES_RO_SERVICE_PORT}/api/v1/namespaces/default/pods/${HOSTNAME} | grep podIP
Although I recommend you use a json parser such as jq
EDIT:
Just wanted to add that pod IP is not preserved across restarts, which is why the usual recommendation is to set up a service pointing to your pod. If you do use a service, the services IP will be fixed and act as a proxy to the pod, even across restarts. Service IPs are provided as environment variables, such as FOO_SERVICE_HOST
and FOO_SERVICE_PORT
.