Kubernetes 简明教程

Kubernetes - Network Policy

网络策略定义了同一个命名空间中的 pod 将如何彼此通信以及网络端点。它要求在 API 服务器的运行时配置中启用 extensions/v1beta1/networkpolicies 。它的资源使用标签选择 pod,并且定义规则以允许流量进入特定的 pod,除了在命名空间中定义的流量。

Network Policy defines how the pods in the same namespace will communicate with each other and the network endpoint. It requires extensions/v1beta1/networkpolicies to be enabled in the runtime configuration in the API server. Its resources use labels to select the pods and define rules to allow traffic to a specific pod in addition to which is defined in the namespace.

首先,我们需要配置命名空间隔离策略。基本上,负载均衡器上需要这种类型的网络策略。

First, we need to configure Namespace Isolation Policy. Basically, this kind of networking policies are required on the load balancers.

kind: Namespace
apiVersion: v1
metadata:
   annotations:
      net.beta.kubernetes.io/network-policy: |
      {
         "ingress":
         {
            "isolation": "DefaultDeny"
         }
      }
$ kubectl annotate ns <namespace> "net.beta.kubernetes.io/network-policy =
{\"ingress\": {\"isolation\": \"DefaultDeny\"}}"

创建命名空间后,我们需要创建网络策略。

Once the namespace is created, we need to create the Network Policy.

Network Policy Yaml

kind: NetworkPolicy
apiVersion: extensions/v1beta1
metadata:
   name: allow-frontend
   namespace: myns
spec:
   podSelector:
      matchLabels:
         role: backend
   ingress:
   - from:
      - podSelector:
         matchLabels:
            role: frontend
   ports:
      - protocol: TCP
         port: 6379