MST

星途 面试题库

面试题:网络编程之Kubernetes网络策略实现

在Kubernetes中,网络策略(NetworkPolicy)是如何实现的?请详细说明如何通过网络策略限制Pod之间的网络访问,包括不同命名空间下Pod的网络隔离策略配置。
18.4万 热度难度
后端开发网络编程

知识考点

AI 面试

面试题答案

一键面试

1. Kubernetes中网络策略的实现基础

Kubernetes网络策略基于网络插件实现,常见的网络插件如Calico、Flannel等。以Calico为例,它使用Linux内核的iptables和ebpf技术来实现网络策略。Calico在每个节点上运行calico-node组件,该组件负责配置和管理iptables规则或ebpf程序,以实现网络策略定义的访问控制。

2. 限制Pod之间网络访问的配置

2.1 同一命名空间内Pod网络访问限制

  • 创建网络策略资源
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: allow-same-namespace-webserver
      namespace: default
    spec:
      podSelector:
        matchLabels:
          app: webserver
      policyTypes:
      - Ingress
      ingress:
      - from:
        - podSelector:
            matchLabels:
              app: backend
        ports:
        - protocol: TCP
          port: 80
    
    • 上述配置表示在default命名空间中,标签为app: webserver的Pod只允许来自标签为app: backend的Pod通过TCP 80端口访问。
    • podSelector指定策略应用的Pod集合。
    • policyTypes指定策略类型,Ingress表示入站策略,还有Egress表示出站策略。
    • ingress部分定义入站规则,from指定允许的源,ports指定允许的端口。

2.2 不同命名空间下Pod网络隔离策略配置

  • 跨命名空间允许访问
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: allow-cross-namespace
      namespace: production
    spec:
      podSelector:
        matchLabels:
          app: api-server
      policyTypes:
      - Ingress
      ingress:
      - from:
        - namespaceSelector:
            matchLabels:
              env: development
          podSelector:
            matchLabels:
              app: test-client
        ports:
        - protocol: TCP
          port: 8080
    
    • 上述配置在production命名空间中,标签为app: api-server的Pod允许来自development标签的命名空间中,标签为app: test-client的Pod通过TCP 8080端口访问。
    • namespaceSelector用于选择命名空间,结合podSelector指定源Pod。
  • 不同命名空间完全隔离
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: isolate-production
      namespace: production
    spec:
      podSelector: {}
      policyTypes:
      - Ingress
      - Egress
      ingress:
      - {}
      egress:
      - {}
    
    • 上述配置应用于production命名空间的所有Pod(podSelector: {}表示匹配所有Pod),通过policyTypes包含IngressEgress,且规则为空,实现与其他命名空间完全隔离(除了Kubernetes系统相关流量)。