Docker容器IP地址一般由docker指定纠炮,什么意思呢?就是用戶在創(chuàng)建容器(默認(rèn)橋接docker0)的時(shí)候無法指定IP郑临!然后問題就來了据过,怎么指定IP颊埃?
相信很多剛接觸docker的人都會(huì)涉及到這個(gè)問題,像所有人一樣蝶俱,我百度了,但是P都沒有饥漫!許多答案都還停留在1榨呆、2年前,過時(shí)了庸队。然后我翻閱了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是可以指定的竿拆!前提是容器橋接的網(wǎng)絡(luò)是用戶創(chuàng)建的宙拉,并且指定了subnet!舉個(gè)例子:
docker network create -o "com.docker.network.bridge.name"="docker1" --subnet 172.20.0.0/16 docker1
指令解析:
- 創(chuàng)建名為docker1的bridge
- --subnet 設(shè)置子網(wǎng)段
- -o "com.docker.network.bridge.name"="docker1" 給這個(gè)bridge起個(gè)名字丙笋,否則宿主機(jī)中看到的網(wǎng)橋名是一坨亂碼谢澈。
然后就是見證奇跡的時(shí)刻:
docker run --rm --ip 172.20.100.100 --net docker1 ubuntu ifconfig
結(jié)果是:
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的地址是預(yù)設(shè)的172.20.100.100!搞定御板!
可是問題又來了锥忿,怎么預(yù)設(shè)容器中網(wǎng)絡(luò)接口的名字呢?比如eth0→foo怠肋?