Can I get ip address inside my docker container?

后端 未结 9 1765
南旧
南旧 2020-12-28 12:10

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

相关标签:
9条回答
  • 2020-12-28 12:22
    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.]+'"
    
    0 讨论(0)
  • 2020-12-28 12:26

    I found solution to my problem:

    /sbin/ip route|awk '/scope/ { print $9 }'
    

    It's print something like: '172.17.0.135'

    0 讨论(0)
  • 2020-12-28 12:31

    Why not something as simple as:

    grep "`hostname`" /etc/hosts|awk '{print $1}'
    

    or

    grep "$HOSTNAME" /etc/hosts|awk '{print $1}'
    
    0 讨论(0)
  • 2020-12-28 12:32

    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

    0 讨论(0)
  • 2020-12-28 12:33

    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).

    0 讨论(0)
  • 2020-12-28 12:33

    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,}.

    0 讨论(0)
提交回复
热议问题