070、如何定制Calico 网络policy(2019-04-15 周一)
Calico默认的policy是:容器只能与同一个calico网络中的容器通信。
Calico能够让用户定义灵活的policy规则,精细化控制进出容器的流量,比如下面的实验:
1、创建一个新的calico网络 cal_web 并部署一个httpd的容器 web1
2、定义policy 允许cal_net2 中的容器访问web1的80端口
更多的policy配置,可参考官方网站http://docs.projectcalico.org/v2.0/reference/calicoctl/resources/policy
# 1、创建calico 网络 cal_web
root@host1:~# docker network create --driver calico --ipam-driver calico-ipam cal_web
88b484859100b4edc3d85aeae8e15d02a05f6c56ea0b2e2a2c820bb460c3fbc4
# 2、在cal_web网络中运行httpd容器 web_server
root@host1:~# docker run -d --name web_server --network cal_web httpd
1d63cea6cfe5b4fb8152100f5d1bc172cb514861e5b442b95873e065f3bb307e
# 3、在cal_net2网络中运行web客户端容器 web_client
root@host1:~# docker run -itd --name web_client --network cal_net2 busybox
55bba02387aa53a5a0ace12a962e58bbda2bb1e8b304811bd739972d30dd5687
# 4、查看web_server 容器ip地址
root@host1:~# docker inspect web_server | jq .[0].NetworkSettings.Networks.cal_web.IPAddress
"192.168.119.2"
# 5、用 cal_net2 网络中的 web_client 访问 cal_web 网络中的 web_server
root@host1:~# docker exec web_client wget http://192.168.119.2
Connecting to 192.168.119.2 (192.168.119.2:80)
wget: can't connect to remote host (192.168.119.2): Connection timed out
# 6、步骤5中的测试没有成功,编辑 cal_web 网络 policy 文件
root@host1:~# cat web.yaml
- apiVersion: v1
kind: profile
metadata:
name: cal_web
spec:
ingress:
- action: allow
protocol: tcp
source:
tag: cal_net2
destination:
ports:
- 80
# 7、应用 cal_web 网络 policy 文件
root@host1:~# calicoctl apply -f web.yaml
Successfully applied 1 'profile' resource(s)
# 8、重新测试 web_client 访问 web_server
root@host1:~# docker exec web_client wget http://192.168.119.2
Connecting to 192.168.119.2 (192.168.119.2:80)
index.html 100% |********************************| 45 0:00:00 ETA
# 9、在host1上查看 cal_web policy
root@host1:~# calicoctl get profile cal_web -o yaml
- apiVersion: v1
kind: profile
metadata:
name: cal_web
spec:
ingress:
- action: allow
destination:
ports:
- 80
protocol: tcp
source:
tag: cal_net2
# 10、在host2上查看 cal_web policy
root@host2:~# calicoctl get profile cal_web -o yaml
- apiVersion: v1
kind: profile
metadata:
name: cal_web
spec:
ingress:
- action: allow
destination:
ports:
- 80
protocol: tcp
source:
tag: cal_net2