Docker容器IP地址一般由docker指定,什么意思呢?就是用户在创建容器(默认桥接docker0)的时候无法指定IP!然后问题就来了,怎么指定IP?
相信很多刚接触docker的人都会涉及到这个问题,像所有人一样,我百度了,但是P都没有!许多答案都还停留在1、2年前,过时了。然后我翻阅了docker docs,看到了下面这句话:
As long as the network to which the container is connecting was created with a user specified subnet, you will be able to select the IPv4 and/or IPv6 address(es) for your container when executing docker run and docker network connect commands by respectively passing the --ip and --ip6 flags for IPv4 and IPv6.
福音啊!IP是可以指定的!前提是容器桥接的网络是用户创建的,并且指定了subnet!举个例子:
docker network create -o "com.docker.network.bridge.name"="docker1" --subnet 172.20.0.0/16 docker1
指令解析:
- 创建名为docker1的bridge
- --subnet 设置子网段
- -o "com.docker.network.bridge.name"="docker1" 给这个bridge起个名字,否则宿主机中看到的网桥名是一坨乱码。
然后就是见证奇迹的时刻:
docker run --rm --ip 172.20.100.100 --net docker1 ubuntu ifconfig
结果是:
eth0 Link encap:Ethernet HWaddr 02:42:ac:14:64:64
inet addr:172.20.100.100 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:acff:fe14:6464/64 Scope:Link
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:1 errors:0 dropped:0 overruns:0 frame:0
TX packets:1 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:90 (90.0 B) TX bytes:90 (90.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
eth0的地址是预设的172.20.100.100!搞定!
可是问题又来了,怎么预设容器中网络接口的名字呢?比如eth0→foo?