建立出來的容器是互相可以ping的。
- pull image
docker image pull busybox
- 建立容器
- –rm :容器停止後會自動刪除
- -name :容器的名字為 box1
- /bin/sh -c “While true; do sleep 3600; done” : 希望執行的命令
docker container run -d --rm --name box1 busybox /bin/sh -c "while true; do sleep 3600; done"
- 檢查容器是否運行中
docker ps
- 進入名為box1的容器
docker exec -it box1 sh
- 查box1的IP
ip a
查看eth0中的IP,如下圖:
- ping看看box1的ip是否有通
$ ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3
- 建立名為box2的新的容器
$ docker container run -d --rm --name box2 busybox /bin/sh -c "while true; do sleep 3600; done"
- 查看目前容器狀況
docker ps
- 查看box2的ip
這次就不進入容器查看,會看到eth0的IP是172.17.0.3
docker exec -it box2 ip a
- 用box1來ping box2
docker exec -it box1 ping 172.17.0.3
結果如下,看起來是有通的:
PING 172.17.0.3 (172.17.0.3): 56 data bytes
64 bytes from 172.17.0.3: seq=0 ttl=64 time=0.159 ms
64 bytes from 172.17.0.3: seq=1 ttl=64 time=0.432 ms
64 bytes from 172.17.0.3: seq=2 ttl=64 time=0.317 ms
64 bytes from 172.17.0.3: seq=3 ttl=64 time=0.384 ms
- pull image nginx
docker image pull nginx
- 創建名為web1的容器
docker run -d --name web1 nginx
- 查看web1的IP
docker inspect web1
補充:因為web沒有安裝ip的指令,所以使用ip a會跳出錯誤訊息
$ docker exec -it web1 ip a
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "ip": executable file not found in $PATH: unknown
- 測試是否相通
進入box1的shell
docker exec -it box1 sh
/ # ping 172.17.0.4
PING 172.17.0.4 (172.17.0.4): 56 data bytes
64 bytes from 172.17.0.4: seq=0 ttl=64 time=0.672 ms
64 bytes from 172.17.0.4: seq=1 ttl=64 time=0.344 ms
64 bytes from 172.17.0.4: seq=2 ttl=64 time=0.307 ms
64 bytes from 172.17.0.4: seq=3 ttl=64 time=0.273 ms
下載172.17.0.4:80的html
/ # wget 172.17.0.4:80
Connecting to 172.17.0.4:80 (172.17.0.4:80)
saving to 'index.html'
index.html 100% |*************************************************************************| 615 0:00:00 ETA
'index.html' saved
查看html檔案
cat index.html
- 端口轉發
建立一個新的container,將80轉到local
docker run -d -p 80:80 --name web2 nginx
- 測試是否有分享到本機
開啟瀏覽器,輸入:
127.0.0.1:80
如果有成功將web2的nginx的80port分享來,會顯示:
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.
For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.
Thank you for using nginx.