Container Mode

  1. 容器模式 (Container Mode) 要先啟動一個容器,使用這個容器建立另一個容器,使用現有的容器 0d30277f64dd,它的 IP 是 172.17.0.2。
    [root@dyw219 ~]# docker inspect 0d30277f64dd | grep 172
            "Gateway": "172.17.42.1",
            "IPAddress": "172.17.0.2",
                    "Gateway": "172.17.42.1",
                    "IPAddress": "172.17.0.2",
    
  2. 使用現有的容器 0d30277f64dd 建立一個新的容器,ID 是 0d30277f64dd。
    [root@dyw219 ~]# docker run --net=container:0d30277f64dd -it centos /bin/bash
    [root@0d30277f64dd /]#
    
  3. 進入容器 0d30277f64dd 後,ping 172.17.42.1, 172.17.0.1, 172.17.0.2 都成功。
    [root@0d30277f64dd /]# ping -c2 172.17.42.1
    PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
    64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.129 ms
    64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.080 ms
    
    --- 172.17.42.1 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 1000ms
    rtt min/avg/max/mdev = 0.080/0.104/0.129/0.026 ms
    
    [root@0d30277f64dd /]# ping -c2 172.17.0.1 
    PING 172.17.0.1 (172.17.0.1) 56(84) bytes of data.
    64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.156 ms
    64 bytes from 172.17.0.1: icmp_seq=2 ttl=64 time=0.087 ms
    
    --- 172.17.0.1 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 1000ms
    rtt min/avg/max/mdev = 0.087/0.121/0.156/0.036 ms
    
    [root@0d30277f64dd /]# ping -c2 172.17.0.2
    PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
    64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.063 ms
    64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.058 ms
    
    --- 172.17.0.2 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 999ms
    rtt min/avg/max/mdev = 0.058/0.060/0.063/0.008 ms
    
  4. 退出容器 0d30277f64dd
    [root@0d30277f64dd /]# exit
    exit
    
  5. 啟動容器 0d30277f64dd
    [root@dyw219 ~]# docker start 0d30277f64dd
    0d30277f64dd
    
  6. 檢查容器 0d30277f64dd 的網路模式是橋接
    [root@dyw219 ~]# docker inspect 0d30277f64dd | grep -i networkmode
            "NetworkMode": "bridge",
    
  7. 檢查容器 0d30277f64dd 的 IP 與容器 0d30277f64dd 的 IP 172.17.0.2 一樣,也就是容器 0d30277f64dd 使用容器 0d30277f64dd 的網卡與 HOST 連線。
    [root@dyw219 ~]# docker inspect 0d30277f64dd | grep 172
            "Gateway": "172.17.42.1",
            "IPAddress": "172.17.0.2",
                    "Gateway": "172.17.42.1",
                    "IPAddress": "172.17.0.2",
    
  8. docker run 使用 centos image 啟動一個名為 dtest5 的容器,執行命令 /bin/bash,網路模式使用 container:dtest2,進入容器後查看主機名稱是否與 dtest2 的 ID 相同?ping dtest2 的 IP 是否成功?退出後,再執行 docker inspect dtest5 查看其主機名稱,使用 pipe grep 過濾 Hostname 字串並導向到 /root/dtest5.container。