kubernetes networkpolicy

慕晨
2023-12-01

1.首先创建namespace隔离策略为DefaultDeny
kind: Namespace
apiVersion: v1
metadata:
  name: testingnp
  annotations:
    net.beta.kubernetes.io/network-policy: |
      {
        "ingress": {
          "isolation": "DefaultDeny"
        }
      }

或者通过命令行对已有namesapce操作
kubectl annotate ns testingnp "net.beta.kubernetes.io/network-policy={\"ingress\": {\"isolation\": \"DefaultDeny\"}}"
通过spec.podSelector.matchLabels 制定操作的pod对象
spec.ingress from/ports来制定允许访问的pod和端口

2.在开启isolation的namespace运行、暴漏服务

kubectl run nginx --image=nginx --replicas=2 --namespace=testingnp
 kubectl expose deployment nginx --port=80  --namespace=testingnp

3.测试连接状态
kubectl run busybox --rm -ti --image=busybox /bin/sh --namespace=testingnp
wget nginx 发现是无法访问的
4.添加networkpolicy
echo '                     
kind: NetworkPolicy
apiVersion: extensions/v1beta1
metadata:
  name: access-nginx
  namespace: testingnp
spec:
  podSelector:
    matchLabels:
      run: nginx
  ingress:
    - from:
      - podSelector:
          matchLabels:
            access: "true"
' | kubectl create  -f -
kubectl get networkpolicies --namespace=testingnp

5.再次验证
制定容器label
kubectl run busybox --rm -ti --labels="access=true" --image=busybox /bin/sh --namespace=testingnp 
wget nginx 可以正常获取资源


 类似资料:

相关阅读

相关文章

相关问答