How to get container ip address inside this container?
\'docker inspect $hostname ...\' not suitable, because I don\'t share /var/run/docker.sock host file to contai
FROM alpine
# Upgrade grep so that it supports -Po flags
RUN apk add --no-cache --upgrade grep
ENV IPADDRESS "ip a show eth0 | grep -Po 'inet \K[\d.]+'"
I found solution to my problem:
/sbin/ip route|awk '/scope/ { print $9 }'
It's print something like: '172.17.0.135'
Why not something as simple as:
grep "`hostname`" /etc/hosts|awk '{print $1}'
or
grep "$HOSTNAME" /etc/hosts|awk '{print $1}'
This may work on some containers if it has the "hostname" command.
docker ps to get the (container id)
docker exec -it (container id) hostname -i
I can find the IP address with
hostname -i
Of course, that may not be completely accurate if there is more than one interface.
Edit
Note: According to the hostname man page, hostname -i
uses DNS to resolve the ip address, where hostname -I
displays all the addresses except loopback, does not depend on DNS, and is recommended.
In all my Docker containers, -i
and -I
return the same results (but this is not the case on my desktop).
You could also look for a line in /etc/hosts that ends with a container id and print the first field:
sed -n 's/^\([0-9\.]*\)[[:blank:]]*[0-9a-f]\{12,\}$/\1/p' /etc/hosts
I'd use awk, but standard awk in dedian:jessie doesn't support regex quantifiers like {12,}
.