天天看點

為docker配置固定ip

docker預設使用bridge模式,通過網橋連接配接到主控端,而容器内部的ip則從網橋所在的ip段取未用的ip。這樣做一個不友善的地方在于容器内部的ip不是固定的,想要連接配接容器時隻能通過映射到主控端的端口,因而有很多項目使用overlay來為docker提供網絡的配置,比如Pipework、Flannel、Kubernetes、Weave、opencontrail等。

想要使用overlay來為docker配置網絡,需要首先了解下docker的網絡模式:

<code>--net=bridge</code> — The default action, that connects the container to the Docker bridge as described above.

<code>--net=container:NAME_or_ID</code> — Tells Docker to put this container's processes inside of the network stack that has already been created inside of another container. The new container's processes will be confined to their own filesystem and process list and resource limits, but will share the same IP address and port numbers as the first container, and processes on the two containers will be able to connect to each other over the loopback interface.

<code>--net=none</code> — Tells Docker to put the container inside of its own network stack but not to take any steps to configure its network, leaving you free to build any of the custom configurations explored in the last few sections of this document.

上面這幾種方式隻有--net=none才可以為docker配置設定固定ip,來看看如何操作。

首先,配置一個用于建立container interface的網橋,可以使用ovs,也可以使用Linux bridge,以Linux bridge為例:

接着,可以啟動容器了,注意用--net=none方式啟動:

下面,為該容器配置網絡namespace,并設定固定ip:

這樣,容器的網絡就配置好了,如果容器内部開啟了sshd服務,通過192.168.33.3就可以直接ssh連接配接到容器,非常友善。上面的步驟比較長,可以借助pipework來為容器設定固定ip(除了設定IP,還封裝了配置網關、macvlan、vlan、dhcp等功能):

pipework docker0 be8365e3b2834 10.88.88.8/24

那麼,當容器需要删除的時候,怎麼清理網絡呢,其實也很簡單: