k8s 网络策略案例

k8s-网络策略案例

1. k8s-网络策略案例

  • 案例1:拒绝其他命名空间Pod访问

  • 案例2:同一个命名空间下应用之间限制访问

  • 案例3:只允许指定命名空间中的应用访问

  • 附:准备环境快捷命令

    kubectl run busybox --image=busybox -n test -- sleep 12h
    
    kubectl run web --image=nginx -n test
    
    kubectl exec busybox -n test --ping 10.244.169.135 
    

2. 案例1: 拒绝其他命名空间Pod访问

  • 需求:test命名空间下所有pod可以互相访问,也可以访问其他命名空间Pod,但其他命名空间不能访问test命名空间Pod。

  • 示例:

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: deny-all-namespaces
      namespace: test
    spec:
      podSelector: {} # 未配置,匹配本命名空间所有pod
      policyTypes:
      - Ingress
      ingress:
      - from:
        - podSelector: {} # 未配置,匹配本命名空间所有pod
    

2.1 案例操作

  • 执行案例

    [root@k8s-master01 ~]# kubectl run busybox --image=busybox -n test -- sleep 12h
    pod/busybox created
    [root@k8s-master01 ~]# kubectl run web --image=nginx -n test
    pod/web created
    
  • 编写配置网络策略

    [root@k8s-master01 ~]# vim test-network.yaml
    [root@k8s-master01 ~]# cat test-network.yaml 
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: deny-all-namespaces
      namespace: test
    spec:
      podSelector: {} # 未配置,匹配本命名空间所有pod
      policyTypes:
      - Ingress
      ingress:
      - from:
        - podSelector: {} # 未配置,匹配本命名空间所有pod
    
  • 执行配置网络策略

    [root@k8s-master01 ~]# kubectl apply -f test-network.yaml 
    networkpolicy.networking.k8s.io/deny-all-namespaces created
    
  • 验证服务

    [root@k8s-master01 ~]# kubectl get pods -n test -o wide
    NAME      READY   STATUS    RESTARTS   AGE   IP              NODE         NOMINATED NODE   READINESS GATES
    busybox   1/1     Running   0          16m   10.244.85.221   k8s-node01   <none>           <none>
    web       1/1     Running   0          15m   10.244.85.222   k8s-node01   <none>           <none>
    [root@k8s-master01 ~]# kubectl exec busybox -n test -- ping 10.244.85.222
    PING 10.244.85.222 (10.244.85.222): 56 data bytes
    64 bytes from 10.244.85.222: seq=0 ttl=63 time=0.169 ms
    64 bytes from 10.244.85.222: seq=1 ttl=63 time=0.063 ms
    64 bytes from 10.244.85.222: seq=2 ttl=63 time=0.065 ms
    
posted @ 2021-12-09 14:56  七月流星雨  阅读(152)  评论(0编辑  收藏  举报