如何限制对某些Kubernetes命名空间的访问,仅允许某些Pod进行访问?

时间:2019-03-12 09:17:42

标签: kubernetes

我提供以下服务:

apiVersion: v1
kind: Service
metadata:
  name: foo
  labels:
    app: foo
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: 8080
      protocol: TCP
      name: foo
  selector:
    app: foo

此服务指向以下部署:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: foo
  labels:
    app: foo
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: foo
  template:
    metadata:
      labels:
        app: foo
    spec:
      containers:
        - name: foo
          image: gcr.io/foo:1.0.0
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 8080

我还有另一个部署:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: bar
  labels:
    app: bar
spec:
  selector:
    matchLabels:
      app: bar
  template:
    metadata:
      labels:
        app: bar
    spec:
      containers:
        - name: bar
          image: gcr.io/bar:1.0.0
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 8080

foo部署到名为kube-protected的Kubernetes命名空间,bar部署到默认的Kubernetes命名空间。

foo包含导入数据,应妥善保护。

Kubernetes的默认名称空间也可能包含其他部署:quxbaz等。

我想限制对服务foo的访问,因此只有bar可以访问它。或者另一种方法是限制对kube-protected名称空间的访问,以便只有bar可以进入它。

解决方案

---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: namespace-which-you-want-to-protect-network-policy
  namespace: namespace-which-you-want-to-protect
spec:
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: namespace-which-is-only-allowed-to-access-protected-namespace
      podSelector:
        matchLabels:
          app: application-which-is-only-allowed-to-access-protected-namespace
  podSelector: {}

1 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用网络策略来限制对 foo

的访问
kind: NetworkPolicy

apiVersion: networking.k8s.io/v1

metadata:

  name: access-nginx

spec:

  podSelector:

    matchLabels:

      app: foo

  ingress:

  - from:

    - podSelector:

        matchLabels:

          app: bar