0
点赞
收藏
分享

微信扫一扫

「走进k8s」Docker 网络模式(六)

(一)网络模式介绍

docker network ls

(二)bridge模式(docker默认的网络模式)

  • ①介绍
sudo yum install net-tools
ifconfig -a

  • ②数据流程
  1. 容器内部发送一条报文,查看路由规则,默认转发到 172.17.0.1(如果是同一个网段,会直接把源地址标记为 172.17.0.2 进行发送)
  2. 通过 eth0 发送的报文,会在 vethXXX 被接收,因为它直接连在 docker0 上,所以默认路由到 docker0
  3. 这个时候报文已经来到了主机上,查询主机的路由表,发现报文应该通过 eth0 从默认网关发送出去,那么报文就被转发给 eth0(就是前面提到的要打开 linux 系统的自动转发配置)
  4. 匹配机器上的 iptables,发现有一条 -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE,也就是 SNAT 规则,那么 linux 内核会修改 ip 源地址为 eth0 的地址,维护一条 NAT 规则记录,然后把报文转发出去。(也就是说对于外部来说,报文是从主机 eth0 发送出去的,无法感知容器的存在)

  • ③流程演示方便理解
docker run --name a1 -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"
docker run --name a2 -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"

docker exec -it a1 /bin/sh 
ifconfig
#查看到a1的ip是172.17.0.2
exit
docker exec -it a2 /bin/sh 
ifconfig
#查看到a2的ip是172.17.0.3
#在a2容器内可以ping通172.17.0.2
ping 172.17.0.2

#在a1容器内尝试ping下a2的ip 172.17.0.3
#在a1容器内可以ping通172.17.0.2
ping 172.17.0.3

docker run --name a2 --link a1 -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"
docker exec -it a2 /bin/sh
ping a1

  • ④自定义网络
docker network create -d bridge net-test

docker run --name test3 --network net-test -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"
docker run --name test4 --network net-test -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"
docker exec -it test3 /bin/sh
ping test4
exit
docker exec -it test4 /bin/sh
ping test3
exit


docker network inspect net-test

(三)host模式(共享主机的网络模式)

#network 更换成host
 docker run --name test5_host --network host -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"  
docker exec -it test5_host  /bin/sh
ifconfig

(四)none模式(空网络模式)

 docker run --name test7_none --network none -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done"  
docker exec -it test7_none /bin/sh
ifconfig

(四)container 模式(容器之前的共享模式,学习k8s这个很重要)

# test7_container 依赖a1的网络模式
 docker run --name test7_container --network container:a1 -d busybox /bin/sh -c "while true;do echo hello docker;sleep 10;done" 
# 分别进入test7_container 和a1查看ifconfig 发现两个是一样的
docker exec -it test7_container /bin/sh
ifconfig
exit
docker exec -it a1 /bin/sh
ifconfig
exit

PS:本次主要讲了4中网络模式:bridge,host,none,container。每个都有自己的场景使用。网络这块是非常重要的。一定要理解。

举报

相关推荐

0 条评论