Docker容器網路設定

2022-08-10 06:01:08

Docker容器網路設定

1、Linux核心實現名稱空間的建立

1.1 ip netns命令

可以藉助ip netns命令來完成對 Network Namespace 的各種操作。ip netns命令來自於iproute安裝包,一般系統會預設安裝,如果沒有的話,請自行安裝。

[root@localhost ~]# dnf -y install iproute

注意:ip netns命令修改網路設定時需要 sudo 許可權。

可以通過ip netns命令完成對Network Namespace 的相關操作,可以通過ip netns help檢視命令幫助資訊:

[root@localhost ~]# ip netns help
Usage:	ip netns list
	ip netns add NAME
	ip netns attach NAME PID
	ip netns set NAME NETNSID
	ip [-all] netns delete [NAME]
	ip netns identify [PID]
	ip netns pids NAME
	ip [-all] netns exec [NAME] cmd ...
	ip netns monitor
	ip netns list-id [target-nsid POSITIVE-INT] [nsid POSITIVE-INT]
NETNSID := auto | POSITIVE-INT

預設情況下,Linux系統中是沒有任何 Network Namespace的,所以ip netns list命令不會返回任何資訊。

1.2 建立Network Namespace

通過命令建立一個名為ns0的名稱空間:

[root@localhost ~]# ip netns list
[root@localhost ~]# ip netns add ns0
[root@localhost ~]# ip netns list
ns0

新建立的 Network Namespace 會出現在/var/run/netns/目錄下。如果相同名字的 namespace 已經存在,命令會報Cannot create namespace file "/var/run/netns/ns0": File exists的錯誤。

[root@localhost ~]# ls /var/run/netns/
ns0
[root@localhost ~]# ip netns add ns0
Cannot create namespace file "/var/run/netns/ns0": File exists

對於每個 Network Namespace 來說,它會有自己獨立的網路卡、路由表、ARP 表、iptables 等和網路相關的資源。

擴充套件:

問:可不可以直接在/var/run/netns/目錄下直接建立一個名稱空間ns2呢?

[root@localhost ~]# touch /var/run/netns/ns2
[root@localhost ~]# ip netns list
Error: Peer netns reference is invalid.
Error: Peer netns reference is invalid.
ns2
ns0

從上得知是不行的

1.3 操作Network Namespace

ip命令提供了ip netns exec子命令可以在對應的 Network Namespace 中執行命令。

檢視新建立 Network Namespace 的網路卡資訊

[root@localhost ~]# ip netns exec ns0 ip a
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

可以看到,新建立的Network Namespace中會預設建立一個lo迴環網路卡,此時網路卡處於關閉狀態。此時,嘗試去 ping 該lo迴環網路卡,會提示Network is unreachable

[root@localhost ~]# ip netns exec ns0 ping 127.0.0.1
connect: Network is unreachable

通過下面的命令啟用lo迴環網路卡:

[root@localhost ~]# ip netns exec ns0 ip link set lo up
[root@localhost ~]# ip netns exec ns0 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
[root@localhost ~]# ip netns exec ns0 ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.031 ms
^C
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.031/0.031/0.031/0.000 ms

1.4 轉移裝置

我們可以在不同的 Network Namespace 之間轉移裝置(如veth)。由於一個裝置只能屬於一個 Network Namespace ,所以轉移後在這個 Network Namespace 內就看不到這個裝置了。

其中,veth裝置屬於可轉移裝置,而很多其它裝置(如lo、vxlan、ppp、bridge等)是不可以轉移的。

1.5 veth pair

veth pair 全稱是 Virtual Ethernet Pair,是一個成對的埠,所有從這對埠一 端進入的封包都將從另一端出來,反之也是一樣。
引入veth pair是為了在不同的 Network Namespace 直接進行通訊,利用它可以直接將兩個 Network Namespace 連線起來。

1.6 建立veth pair

[root@localhost ~]# ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
    link/ether 00:0c:29:bb:22:82 brd ff:ff:ff:ff:ff:ff
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default 
    link/ether 02:42:f0:ef:67:fd brd ff:ff:ff:ff:ff:ff
14: veth0@veth1: <BROADCAST,MULTICAST,M-DOWN> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether 92:53:e7:1c:f2:8c brd ff:ff:ff:ff:ff:ff
15: veth1@veth0: <BROADCAST,MULTICAST,M-DOWN> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether 56:2b:0c:45:fb:03 brd ff:ff:ff:ff:ff:ff

可以看到,此時系統中新增了一對veth pair,將veth0和veth1兩個虛擬網路卡連線了起來,此時這對 veth pair 處於」未啟用「狀態。

1.7 實現Network Namespace間通訊

下面我們利用veth pair實現兩個不同的 Network Namespace 之間的通訊。剛才我們已經建立了一個名為ns0的 Network Namespace,下面再建立一個資訊Network Namespace,命名為ns1

[root@localhost ~]# ip netns add ns1
[root@localhost ~]# ip netns list
ns1
ns0

然後我們將veth0加入到ns0,將veth1加入到ns1

[root@localhost ~]# ip link set veth0 netns ns0
[root@localhost ~]# ip link set veth1 netns ns1

然後我們分別為這對veth pair設定上ip地址,並啟用它們

[root@localhost ~]# ip netns exec ns0 ip link set veth0 up
[root@localhost ~]# ip netns exec ns0 ip addr add 192.168.100.1/24 dev veth0
[root@localhost ~]# ip netns exec ns1 ip link set lo up
[root@localhost ~]# ip netns exec ns1 ip link set veth1 up
[root@localhost ~]# ip netns exec ns1 ip addr add 192.168.100.2/24 dev veth1

檢視這對veth pair的狀態

[root@localhost ~]# ip netns exec ns0 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
14: veth0@if15: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 92:53:e7:1c:f2:8c brd ff:ff:ff:ff:ff:ff link-netns ns1
    inet 192.168.100.1/24 scope global veth0
       valid_lft forever preferred_lft forever
    inet6 fe80::9053:e7ff:fe1c:f28c/64 scope link 
       valid_lft forever preferred_lft forever
[root@localhost ~]# ip netns exec ns1 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
15: veth1@if14: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 56:2b:0c:45:fb:03 brd ff:ff:ff:ff:ff:ff link-netns ns0
    inet 192.168.100.2/24 scope global veth1
       valid_lft forever preferred_lft forever
    inet6 fe80::542b:cff:fe45:fb03/64 scope link 
       valid_lft forever preferred_lft forever

從上面可以看出,我們已經成功啟用了這個veth pair,併為每個veth裝置分配了對應的ip地址。我們嘗試在ns1中存取ns0中的ip地址:

[root@localhost ~]# ip netns exec ns1 ping 192.168.100.1
PING 192.168.100.1 (192.168.100.1) 56(84) bytes of data.
64 bytes from 192.168.100.1: icmp_seq=1 ttl=64 time=0.051 ms
^C
--- 192.168.100.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.051/0.051/0.051/0.000 ms

可以看到,veth pair成功實現了兩個不同Network Namespace之間的網路互動。

1.8 veth裝置重新命名

# 需要先停用裝置才能重新命名
[root@localhost ~]# ip netns exec ns0 ip link set dev veth0 name zsl0
RTNETLINK answers: Device or resource busy

# 停用veth0
[root@localhost ~]# ip netns exec ns0 ip link set veth0 down

# 將veth0重新命名為zsl0
[root@localhost ~]# ip netns exec ns0 ip link set dev veth0 name zsl0

# 啟用zsl0
[root@localhost ~]# ip netns exec ns0 ip link set zsl0 up

# 檢視是否修改成功
[root@localhost ~]# ip netns exec ns0 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
14: zsl0@if15: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 92:53:e7:1c:f2:8c brd ff:ff:ff:ff:ff:ff link-netns ns1
    inet 192.168.100.1/24 scope global zsl0
       valid_lft forever preferred_lft forever
    inet6 fe80::9053:e7ff:fe1c:f28c/64 scope link 
       valid_lft forever preferred_lft forever

擴充套件:

建立veth pair,一個給名稱空間a1,一個給本機,並且都配上ip地址,兩個能相互通訊嗎?

# 建立名稱空間a1
[root@localhost ~]# ip netns add a1
[root@localhost ~]# ip netns list
a1

# 建立veth pair
[root@localhost ~]# ip link add type veth

# 將veth1給a1
[root@localhost ~]# ip link set veth1 netns a1

# 啟用主機和a1的虛擬網路卡
[root@localhost ~]# ip link set veth0 up
[root@localhost ~]# ip netns exec a1 ip link set lo up
[root@localhost ~]# ip netns exec a1 ip link set veth1 up

# 給主機的veth0配上ip地址
[root@localhost ~]# ip addr add 192.168.200.1/24 dev veth0
[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:bb:22:82 brd ff:ff:ff:ff:ff:ff
    inet 192.168.111.135/24 brd 192.168.111.255 scope global dynamic noprefixroute ens160
       valid_lft 1524sec preferred_lft 1524sec
    inet6 fe80::3d5c:b9d6:55f:48e9/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:ac:46:f8:53 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
4: veth0@if5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 2e:f3:88:07:d4:97 brd ff:ff:ff:ff:ff:ff link-netns a1
    inet 192.168.200.1/24 scope global veth0
       valid_lft forever preferred_lft forever
    inet6 fe80::2cf3:88ff:fe07:d497/64 scope link 
       valid_lft forever preferred_lft forever

# 給a1的veth1配上ip地址
[root@localhost ~]# ip netns exec a1 ip addr add 192.168.200.2/24 dev veth1
[root@localhost ~]# ip netns exec a1 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
5: veth1@if4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 4a:87:cf:df:f6:46 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 192.168.200.2/24 scope global veth1
       valid_lft forever preferred_lft forever
    inet6 fe80::4887:cfff:fedf:f646/64 scope link 
       valid_lft forever preferred_lft forever

# 用主機ping名稱空間a1的veth1測試
[root@localhost ~]#  ping 192.168.200.2
PING 192.168.200.2 (192.168.200.2) 56(84) bytes of data.
64 bytes from 192.168.200.2: icmp_seq=1 ttl=64 time=0.098 ms
64 bytes from 192.168.200.2: icmp_seq=2 ttl=64 time=0.095 ms
^C
--- 192.168.200.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1045ms
rtt min/avg/max/mdev = 0.095/0.096/0.098/0.009 ms

從上得知是可以相互通訊的

2、四種網路模式設定

2.1 bridge模式設定

在建立容器時新增--network bridge與不加--network選項效果是一致的

# 新增--network bridge
[root@localhost ~]# docker run -it --rm --network bridge busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

# 不加--network bridge
[root@localhost ~]# docker run -it --rm busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
8: eth0@if9: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

2.2 none模式設定

[root@localhost ~]# docker run -it --rm --network none busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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

# 以上是docker容器幫你做好了,與自己開闢名稱空間效果相同
[root@localhost ~]# ip netns add z1
[root@localhost ~]# ip netns exec z1 ip link set lo up 
[root@localhost ~]# ip netns exec z1 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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

2.3 container模式設定

啟動第一個容器web1

[root@localhost ~]# docker run -it --rm --name web1 busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
4: eth0@if5: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

啟動第二個容器web2

[root@localhost ~]# docker run -it --rm --name web2 busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

可以看到名為web2的容器IP地址是172.17.0.3,與第一個容器的IP地址不是一樣的,也就是說並沒有共用網路,此時如果我們將第二個容器的啟動方式改變一下,就可以使名為web2的容器IP與web1容器IP一致,也即共用IP,但不共用檔案系統。

[root@localhost ~]# docker run -it --rm --name web2 --network container:web1 busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
4: eth0@if5: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

此時我們在web1容器上建立一個目錄

/ # mkdir /tmp/data
/ # ls /tmp/
data

到web2容器上檢查/tmp目錄會發現並沒有這個目錄,因為檔案系統是處於隔離狀態,僅僅是共用了網路而已。

在web2容器上部署一個站點

/ # echo 'hello word' > /tmp/index.html
/ # ls /tmp/
index.html
/ # httpd -h /tmp
/ # netstat -anlt
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
tcp        0      0 :::80                   :::*                    LISTEN    

在web1容器上用本地地址去存取此站點

/ # wget -O - -q 127.0.0.1:80
hello word

由此可見,container模式下的容器間關係就相當於一臺主機上的兩個不同程序

2.4 host模式設定

啟動容器時直接指明模式為host

[root@localhost ~]# docker run -it --rm --network host busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel qlen 1000
    link/ether 00:0c:29:bb:22:82 brd ff:ff:ff:ff:ff:ff
    inet 192.168.111.135/24 brd 192.168.111.255 scope global dynamic noprefixroute ens160
       valid_lft 1121sec preferred_lft 1121sec
    inet6 fe80::3d5c:b9d6:55f:48e9/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue 
    link/ether 02:42:54:0c:19:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:54ff:fe0c:1902/64 scope link 
       valid_lft forever preferred_lft forever

此時如果我們在這個容器中啟動一個http站點,我們就可以直接用宿主機的IP直接在瀏覽器中存取這個容器中的站點了。

/ # echo 'hello word' > /tmp/index.html
/ # httpd -h /tmp
/ # netstat -anlt
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      
tcp        0      0 192.168.111.135:22      192.168.111.1:1052      ESTABLISHED 
tcp        0      0 :::80                   :::*                    LISTEN      
tcp        0      0 :::22                   :::*                    LISTEN  

[root@localhost ~]# ss -anlt
State        Recv-Q       Send-Q             Local Address:Port             Peer Address:Port      Process       
LISTEN       0            128                      0.0.0.0:22                    0.0.0.0:*                       
LISTEN       0            9                              *:80                          *:*                       
LISTEN       0            128                         [::]:22                       [::]:*                       
[root@localhost ~]# curl 192.168.111.135
hello word

擴充套件:

問:此時還能在建立一個容器再部署一個http站點嗎?

[root@localhost ~]# docker run -it --rm --network host busybox
/ # echo 'hello word' > /tmp/index.html
/ # httpd -h /tmp
httpd: bind: Address already in use

從上得知是是不能的,因為埠會衝突。

3、容器的常用操作

3.1 檢視容器的主機名

[root@localhost ~]# docker run -it --rm busybox
/ # hostname
a7898c7df6f9
# 主機名預設為容器的ID
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED              STATUS        PORTS     NAMES
a7898c7df6f9   busybox   "sh"      About a minute ago   Up About a minute          priceless_swartz

# 無法修改主機名,因為是唯讀狀態
/ # hostname zsl
hostname: sethostname: Operation not permitted

3.2 在容器啟動時注入主機名

[root@localhost ~]# docker run -it --rm --hostname zsl busybox
/ # hostname
zsl

# 容器ID不會因為指定hostname而改變成一致
CONTAINER ID   IMAGE     COMMAND   CREATED          STATUS          PORTS     NAMES
7558f343d7b7   busybox   "sh"      33 seconds ago   Up 32 seconds             objective_hoover

# 注入主機名時會自動建立主機名到IP的對映關係
/ # cat /etc/hosts
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
172.17.0.2	zsl

# DNS也會自動設定為宿主機的DNS
/ # cat /etc/resolv.conf 
# Generated by NetworkManager
search localdomain
nameserver 192.168.111.2

# ping zsl
/ # ping zsl
PING zsl (172.17.0.2): 56 data bytes
64 bytes from 172.17.0.2: seq=0 ttl=64 time=0.028 ms
64 bytes from 172.17.0.2: seq=1 ttl=64 time=0.113 ms
^C
--- zsl ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.028/0.070/0.113 ms

3.3 手動指定容器要使用的DNS

[root@localhost ~]# docker run -it --rm --hostname zsl --dns 8.8.8.8 busybox
/ # cat /etc/resolv.conf 
search localdomain
nameserver 8.8.8.8
/ # cat /etc/hostname 
zsl
/ # ping www.baidu.com
PING www.baidu.com (36.152.44.95): 56 data bytes
64 bytes from 36.152.44.95: seq=0 ttl=127 time=20.362 ms
64 bytes from 36.152.44.95: seq=1 ttl=127 time=35.127 ms
^C
--- www.baidu.com ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 20.362/27.744/35.127 ms

3.4 手動往/etc/hosts檔案中注入主機名到IP地址的對映

如果要對映多個主機名就用多個--hostname

[root@localhost ~]# docker run -it --rm busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
14: eth0@if15: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # hostname
c582a2f0d137

(另開一個終端)
# 對映172.17.0.2為zsl2
[root@localhost ~]# docker run -it --rm --hostname zsl1 --dns 8.8.8.8 --add-host zsl2:172.17.0.2 busybox
/ # cat /etc/hosts 
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
172.17.0.2	zsl2
172.17.0.3	zsl1
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
18: eth0@if19: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

/ # ping zsl1
PING zsl1 (172.17.0.3): 56 data bytes
64 bytes from 172.17.0.3: seq=0 ttl=64 time=0.043 ms
^C
--- zsl1 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.043/0.043/0.043 ms

/ # ping zsl2
PING zsl2 (172.17.0.2): 56 data bytes
64 bytes from 172.17.0.2: seq=0 ttl=64 time=0.149 ms
64 bytes from 172.17.0.2: seq=1 ttl=64 time=0.162 ms
^C
--- zsl2 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.149/0.155/0.162 ms

3.5 開放容器埠

執行docker run的時候有個-p選項,可以將容器中的應用埠對映到宿主機中,從而實現讓外部主機可以通過存取宿主機的某埠來存取容器內應用的目的。

-p選項能夠使用多次,其所能夠暴露的埠必須是容器確實在監聽的埠。

-p選項的使用格式:

  • -p
    • 將指定的容器埠對映至主機所有地址的一個動態埠
  • -p :
    • 將容器埠對映至指定的主機埠
  • -p ::
    • 將指定的容器埠對映至主機指定的動態埠
  • -p ::
    • 將指定的容器埠對映至主機指定的埠

範例:

-p (containerPort)

將指定的容器埠對映至主機所有地址的一個動態埠

[root@localhost ~]# docker run -d -p 80 httpd
5d969f5c435c02164caf5945ba2a0f5d0ff3c8b7d3e6217adc5c03f855b1c028
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS          PORTS                                     NAMES
5d969f5c435c   httpd     "httpd-foreground"   28 seconds ago   Up 27 seconds   0.0.0.0:49153->80/tcp, :::49153->80/tcp   competent_payne
[root@localhost ~]# ss -anlt
State           Recv-Q          Send-Q                   Local Address:Port                    Peer Address:Port         Process         
LISTEN          0               128                            0.0.0.0:22                           0.0.0.0:*                            
LISTEN          0               128                            0.0.0.0:49153                        0.0.0.0:*                            
LISTEN          0               128                               [::]:22                              [::]:*                            
LISTEN          0               128                               [::]:49153                           [::]:*   
[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 192.168.111.135:49153
<html><body><h1>It works!</h1></body></html>

-p (hostPort):(containerPort)

將容器埠(containerPort)對映至指定的主機埠(hostPort)

[root@localhost ~]# docker run -d -p 8080:80 httpd
554dc98f55155d31e6b79adedda74c937eaf4459582a088bae5d2e3fbfb25307
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND              CREATED         STATUS         PORTS                                   NAMES
554dc98f5515   httpd     "httpd-foreground"   9 seconds ago   Up 8 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   distracted_galileo
[root@localhost ~]# ss -anlt
State           Recv-Q          Send-Q                   Local Address:Port                   Peer Address:Port         Process          
LISTEN          0               128                            0.0.0.0:8080                        0.0.0.0:*                             
LISTEN          0               128                            0.0.0.0:22                          0.0.0.0:*                             
LISTEN          0               128                               [::]:8080                           [::]:*                             
LISTEN          0               128                               [::]:22                             [::]:*                             

[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 192.168.111.135:8080
<html><body><h1>It works!</h1></body></html>

-p (ip)::(containerPort)

將指定的容器埠(containerPort)對映至主機指定(ip)的動態埠

[root@localhost ~]# docker run -d -p 192.168.111.135::80 httpd
edde41dc824b45b2aafd50e41268a19faf0f31d11a43c67c821d0b8fa997ecec
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND              CREATED         STATUS         PORTS                           NAMES
edde41dc824b   httpd     "httpd-foreground"   7 seconds ago   Up 5 seconds   192.168.111.135:49153->80/tcp   strange_curie
[root@localhost ~]# ss -anlt
State          Recv-Q         Send-Q                     Local Address:Port                    Peer Address:Port         Process         
LISTEN         0              128                              0.0.0.0:22                           0.0.0.0:*                            
LISTEN         0              128                      192.168.111.135:49153                        0.0.0.0:*                            
LISTEN         0              128                                 [::]:22                              [::]:*   
root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 192.168.111.135:49153
<html><body><h1>It works!</h1></body></html>

-p (ip):(hostPort):(containerPort)

將指定的容器埠(containerPort)對映至主機指定(ip)的埠(hostPort)

[root@localhost ~]# docker run -d -p 192.168.111.135:80:80 httpd
c044e47fbff6473c26df06a78f523b9683e60ac906e136799669dba47d92059a
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND              CREATED         STATUS         PORTS                        NAMES
c044e47fbff6   httpd     "httpd-foreground"   5 seconds ago   Up 4 seconds   192.168.111.135:80->80/tcp   mystifying_chatterjee
[root@localhost ~]# ss -anlt
State          Recv-Q          Send-Q                     Local Address:Port                   Peer Address:Port         Process         
LISTEN         0               128                      192.168.111.135:80                          0.0.0.0:*                            
LISTEN         0               128                              0.0.0.0:22                          0.0.0.0:*                            
LISTEN         0               128                                 [::]:22                             [::]:*                            

[root@localhost ~]# curl 172.17.0.2
<html><body><h1>It works!</h1></body></html>
[root@localhost ~]# curl 192.168.111.135:80
<html><body><h1>It works!</h1></body></html>

動態埠指的是隨機埠,具體的對映結果可使用docker port命令檢視。

[root@localhost ~]# docker port c044e47fbff6
80/tcp -> 192.168.111.135:80

注意:

iptables防火牆規則將隨容器的建立自動生成,隨容器的刪除自動刪除規則。

3.6 自定義docker0網橋的網路屬性資訊

自定義docker0網橋的網路屬性資訊很多,以下只演示bip,更多詳情見官方檔案相關設定

需要修改/etc/docker/daemon.json組態檔

[root@localhost ~]# vim /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://6vrrj6n2.mirror.aliyuncs.com"],
  "bip": "192.168.100.1/24"
}
[root@localhost ~]# systemctl daemon-reload 
[root@localhost ~]# systemctl restart docker
[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:bb:22:82 brd ff:ff:ff:ff:ff:ff
    inet 192.168.111.135/24 brd 192.168.111.255 scope global dynamic noprefixroute ens160
       valid_lft 1224sec preferred_lft 1224sec
    inet6 fe80::3d5c:b9d6:55f:48e9/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:35:39:6d:e6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.1/24 brd 192.168.100.255 scope global docker0
       valid_lft forever preferred_lft forever

# 網橋修改後,建立出來的容器虛擬網路卡IP地址規律也會改變
[root@localhost ~]# docker run -it --rm busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
4: eth0@if5: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:64:02 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.2/24 brd 192.168.100.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.100.1   0.0.0.0         UG    0      0        0 eth0
192.168.100.0   0.0.0.0         255.255.255.0   U     0      0        0 eth0

核心選項為bip,即bridge ip之意,用於指定docker0橋自身的IP地址;其它選項可通過此地址計算得出。

3.7 Docker 遠端連線

dockerd守護行程的C/S,其預設僅監聽Unix Socket格式的地址(/var/run/docker.sock),如果要使用TCP通訊端,則需要修改/etc/docker/daemon.json組態檔,新增如下內容,然後重啟docker服務:

[root@localhost ~]# vim /lib/systemd/system/docker.service 
......
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock -H unix:///run/docker.sock -H tcp://0.0.0.0:2375
......
[root@localhost ~]# systemctl daemon-reload 
[root@localhost ~]# systemctl restart docker

在使用者端上向dockerd直接傳遞「-H|--host」選項指定要控制哪臺主機上的docker容器

[root@localhost ~]# docker -H 192.168.111.135:2375 ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

3.8 Docker建立自定義橋接網路

建立一個額外的自定義橋,區別於docker0

[root@localhost ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
90e83c543376   bridge    bridge    local
38bb8b947433   host      host      local
c74fce351c8a   none      null      local

[root@localhost ~]# docker network create -d bridge --subnet "192.168.1.0/24" --gateway "192.168.1.1" br0
a932f50dbb6bff81a904962fda8f7ec348ac2dfdab0833e339a988b85b7926f3

[root@localhost ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
a932f50dbb6b   br0       bridge    local
90e83c543376   bridge    bridge    local
38bb8b947433   host      host      local
c74fce351c8a   none      null      local

[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    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
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:bb:22:82 brd ff:ff:ff:ff:ff:ff
    inet 192.168.111.135/24 brd 192.168.111.255 scope global dynamic noprefixroute ens160
       valid_lft 1042sec preferred_lft 1042sec
    inet6 fe80::3d5c:b9d6:55f:48e9/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:35:39:6d:e6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.1/24 brd 192.168.100.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:35ff:fe39:6de6/64 scope link 
       valid_lft forever preferred_lft forever
6: br-a932f50dbb6b: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:ee:0a:b3:e1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.1/24 brd 192.168.1.255 scope global br-a932f50dbb6b
       valid_lft forever preferred_lft forever

使用新建立的自定義橋來建立容器c2:

[root@localhost ~]# docker run -it --name c2 --network br0 busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
7: eth0@if8: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:01:02 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.2/24 brd 192.168.1.255 scope global eth0
       valid_lft forever preferred_lft forever

再建立一個容器c1,使用預設的bridge橋:

[root@localhost ~]#  docker run -it --name c1 --network bridge busybox
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
9: eth0@if10: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:64:02 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.2/24 brd 192.168.100.255 scope global eth0
       valid_lft forever preferred_lft forever

試想一下,此時的c1(192.168.100.2)與c2(192.168.1.2)能否互相通訊?如果不能該如何實現通訊?

給容器新增網路

# 給c1加br0
[root@localhost ~]# docker network connect br0 c1

# 容器c1:
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
13: eth0@if14: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:64:02 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.2/24 brd 192.168.100.255 scope global eth0
       valid_lft forever preferred_lft forever
15: eth1@if16: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:01:03 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.3/24 brd 192.168.1.255 scope global eth1
       valid_lft forever preferred_lft forever

# ping c2
/ # ping 192.168.1.2
PING 192.168.1.2 (192.168.1.2): 56 data bytes
64 bytes from 192.168.1.2: seq=0 ttl=64 time=0.127 ms
64 bytes from 192.168.1.2: seq=1 ttl=64 time=0.102 ms
^C
--- 192.168.1.2 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.102/0.114/0.127 ms

# 給c2加bridge
[root@localhost ~]# docker network connect bridge c2

# 容器c2:
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    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
11: eth0@if12: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:01:02 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.2/24 brd 192.168.1.255 scope global eth0
       valid_lft forever preferred_lft forever
17: eth1@if18: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether 02:42:c0:a8:64:03 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.3/24 brd 192.168.100.255 scope global eth1
       valid_lft forever preferred_lft forever

# ping c1測試
/ # ping 192.168.100.2
PING 192.168.100.2 (192.168.100.2): 56 data bytes
64 bytes from 192.168.100.2: seq=0 ttl=64 time=0.226 ms
64 bytes from 192.168.100.2: seq=1 ttl=64 time=0.088 ms
^C
--- 192.168.100.2 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.088/0.157/0.226 ms

由上可見,c1(192.168.100.2)與c2(192.168.1.2)能互相通訊。