本示例使用基于calico的網絡策略實驗。
實驗目的,使用策略規(guī)則,建立簡單的網絡隔離。
創(chuàng)建命名空間 policy-demo
kubectl create ns policy-demo
創(chuàng)建 demo pod
1、 在命名空間中創(chuàng)建nginx pod
kubectl create deployment --namespace=policy-demo nginx --image=nginx
2、開放service端口
kubectl expose --namespace=policy-demo deployment nginx --port=80
3、確認nginx service能夠訪問
創(chuàng)建一個busybox,使用wget命令驗證
kubectl run --namespace=policy-demo access --rm -ti --image busybox /bin/sh
[root@k8s-master ~]# kubectl run --namespace=policy-demo access --rm -ti --image busybox /bin/sh
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
If you don't see a command prompt, try pressing enter.
/ # wget -q nginx -O -
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a >nginx.org</a>.<br/>
Commercial support is available at
<a >nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
使用策略隔離
創(chuàng)建一個命名空間policy-demo中所有pod都默認給拒絕的行為。
kubectl create -f - <<EOF
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: default-deny
namespace: policy-demo
spec:
podSelector:
matchLabels: {}
EOF
隔離驗證
阻止所有要訪問nginx service
kubectl run --namespace=policy-demo access --rm -ti --image busybox /bin/sh
wget -q --timeout=5 nginx -O -
wget: download timed out
允許使用網絡策略訪問
kubectl create -f - <<EOF
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: access-nginx
namespace: policy-demo
spec:
podSelector:
matchLabels:
app: nginx
ingress:
- from:
- podSelector:
matchLabels:
run: access
EOF
這個策略規(guī)則允許流量從帶標簽run: access的pod到達帶標簽app: nginx。
現(xiàn)在能夠從access的pod訪問service
kubectl run --namespace=policy-demo cant-access --rm -ti --image busybox /bin/sh
wget -q --timeout=5 nginx -O -