Kubernetes Network Policies 网络策略

Kubernetes Network Policies

Posted by BlueFat on Wednesday, November 25, 2020

https://kubernetes.io/docs/concepts/services-networking/network-policies/

Network Policy提供了基于策略的网络控制,用于隔离应用并减少攻击面。它使用标签选择器模拟传统的分段网络,并通过策略控制它们之间的流量以及来自外部的流量。

网络策略由网络插件实现。要使用网络策略,您必须使用支持 NetworkPolicy 的网络解决方案如Calico、Romana、Weave Net和trireme等。 在没有实现它的控制器的情况下创建 NetworkPolicy 资源将无效。

Pod隔离

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      role: db  # 对当前namespace default中Pod带有role=db标签生效
  policyTypes:
    - Ingress
    - Egress
  ingress:  # 入站规则
    - from:
        - ipBlock:
            cidr: 172.17.0.0/16  # 允许网段
            except:
              - 172.17.1.0/24   # 排除网段
        - namespaceSelector:
            matchLabels:
              project: myproject  # 允许标签带有project=myproject namespace访问
        - podSelector:
            matchLabels:
              role: frontend  # 允许当前namespace Pod带有role=frontend标签访问
      ports:
        - protocol: TCP  # 支持的协议有TCP, UDP, SCTP
          port: 6379
  egress:  # 出站规则
  - {}    # 允许所有出站规则

1.默认禁止所有入pod流量

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Ingress

2.默认允许所有入pod流量

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all
spec:
  podSelector: {}
  ingress:
  - {}

3.默认禁止所有出pod流量

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Egress

4.默认允许所有出pod流量

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all
spec:
  podSelector: {}
  egress:
  - {}
  policyTypes:
  - Egress

5.默认禁止所有入出pod流量

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

注:pod与所运行节点之间流量不受Network Policy限制