當docker以橋接的方式啟動容器時,容器內部的IP是經過DHCP獲取的,例如:172.17.0.8/32,且每重啟依次IP都會發生變動。某些特殊的情況下,需要容器內有自己固定的一個內部IP。我的實現方法如下:
1、啟動docker容器
# docker run -tid -p 4097:8080 --restart=always --privileged=true --log-driver=none --cap-add=NET_ADMIN 10.0.224.83:5000/centos /run.sh
其中關鍵的選項是--privileged=true和--cap-add=NET_ADMIN。
2、進入容器,在/run.sh中新增如下,為容器新增額外的固定IP
/sbin/ip addr add 172.17.1.250 dev eth0
3、重啟容器,再次進入容器檢視IP
[root@07be2449da38 /]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 154: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP link/ether 02:42:ac:11:00:39 brd ff:ff:ff:ff:ff:ff inet 172.17.0.57/16 scope global eth0 valid_lft forever preferred_lft forever inet 172.17.1.250/32 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::42:acff:fe11:39/64 scope link valid_lft forever preferred_lft forever
4、宿主機上ping該地址
[root@localhost log]# ping 172.17.1.250 PING 172.17.1.250 (172.17.1.250) 56(84) bytes of data. 64 bytes from 172.17.1.250: icmp_seq=1 ttl=64 time=0.050 ms 64 bytes from 172.17.1.250: icmp_seq=2 ttl=64 time=0.069 ms