Host Mode

  1. 主機模式 (Host Mode) 建立一個與 Host 同樣網路界面的容器,使用方式如下:
    [root@dyw219 ~]# docker run --net=host -it centos /bin/bash
    
  2. 進入容器 shell 後,提示字符上的主機名稱與 docker host 一樣。
    [root@dyw219 /]# hostname
    dyw219
    
  3. ping 172.17.42.1, 172.17.0.1, 172.17.0.2 都成功。
    [root@dyw219 /]# 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.089 ms
    64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.065 ms
    
    --- 172.17.42.1 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 999ms
    rtt min/avg/max/mdev = 0.065/0.077/0.089/0.012 ms
    
    [root@dyw219 /]# 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.085 ms
    64 bytes from 172.17.0.1: icmp_seq=2 ttl=64 time=0.065 ms
    
    --- 172.17.0.1 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 999ms
    rtt min/avg/max/mdev = 0.065/0.075/0.085/0.010 ms
    
    [root@dyw219 /]# 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.093 ms
    64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.070 ms
    
    --- 172.17.0.2 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 999ms
    rtt min/avg/max/mdev = 0.070/0.081/0.093/0.014 ms
    
  4. 退出容器
    [root@dyw219 /]# exit
    exit
    
  5. 檢查容器 9facf9a147fd 的網路模式
    [root@dyw219 ~]# docker inspect 9facf9a147fd | grep -i networkmode
            "NetworkMode": "host",
    
  6. docker run 使用 nandrade1/php-apache image 啟動一個名為 dtest3 的容器於背景 (backgroup)。啟動後,再執行 docker inspect dtest3 查看其主機名稱,使用 pipe grep 過濾 Hostname 字串並導向到 /root/dtest3.host。