NetworkPolicy

NetworkPolicy is an object designed by Kubernetes to restrict Pod access. By setting the NetworkPolicy policy, you can allow the Pod to be accessed by which addresses (that is, inbound rules), or which addresses the Pod can access (that is, outbound rules). This is equivalent to building a firewall from the application level to further ensure network security.

The capabilities supported by NetworkPolicy depend on the capabilities of the cluster's network plug-in. For example, a CCE cluster only supports setting Pod entry rules.

By default, if no policy exists in the namespace, all traffic entering and exiting the Pod in the namespace is allowed.

There are 3 types of NetworkPolicy rules:

  • namespaceSelector: According to the label selection of the namespace, all the namespaces with this label can be accessed.
  • podSelector: According to the Pod's label selection, all Pods with this label can be accessed.
  • ipBlock: According to network selection, all IP addresses in the network segment can be accessed. (CCE does not currently support this method)

    Use podSelector to set the access range

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
    name: test-network-policy
    namespace: default
    spec:
    podSelector:
    matchLabels:
      role: db
    ingress:                      # 表示入规则
    - from:
    - podSelector:              # 只允许具有role=frontend标签的Pod访问
        matchLabels:
          role: frontend
    ports:                      # 只能使用TCP协议访问6379端口
    - protocol: TCP
      port: 6379

The schematic diagram is shown below.

Figure 1 podSelector

NetworkPolicy

Use namespaceSelector to set the access range

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
spec:
  podSelector:
    matchLabels:
      role: db
  ingress:                      # 表示入规则
  - from:
    - namespaceSelector:        # 只允许具有project=myproject标签的命名空间中的Pod访问
        matchLabels:
          project: myproject
    ports:                      # 只能使用TCP协议访问6379端口
    - protocol: TCP
      port: 6379

The schematic diagram is shown below.

Figure 2 namespaceSelector
NetworkPolicy

Guess you like

Origin blog.51cto.com/14051317/2553825