网络策略--简单示例

本示例使用基于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 -
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • https://edu.aliyun.com/course/1651 第一章 云原生课 1.1 云原生技术发展历程...
    MichelleZm阅读 1,755评论 0 0
  • 1、Network 接下来就要说到跟Kubernetes网络通信相关的内容,我们都知道K8S最小的操作单位是Pod...
    Suny____阅读 568评论 0 3
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,609评论 16 22
  • 创业是很多人的梦想,多少人为了理想和不甘选择了创业来实现自我价值,我就是其中一个。 创业后,我由女人变成了超人,什...
    亦宝宝阅读 1,910评论 4 1
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,627评论 0 11