网络策略--简单示例

2020-08-06  本文已影响0人  杀破魂

本示例使用基于calico的网络策略实验。

实验目的,使用策略规则,建立简单的网络隔离。

创建命名空间 policy-demo

kubectl create ns policy-demo

创建 demo pod

1、 在命名空间中创建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能够访问
创建一个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 href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

使用策略隔离

创建一个命名空间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

这个策略规则允许流量从带标签run: access的pod到达带标签app: nginx

现在能够从access的pod访问service

kubectl run --namespace=policy-demo cant-access --rm -ti --image busybox /bin/sh
wget -q --timeout=5 nginx -O -
上一篇 下一篇

猜你喜欢

热点阅读