How to restrict access to some Kubernetes namespace allowing access only by some pods?

3/12/2019

I have the following service:

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

This service point to the following deployment:

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

I also have another deployment:

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 is deployed to Kubernetes namespace called kube-protected, bar is deployed to default Kubernetes namespace.

foo contains import data and should be well secured.

Kubernetes default namespace may also contain another deployments: qux, baz, etc.

I want to restrict access to service foo so only bar can access it. Or another way is to restrict access to kube-protected namespace so only bar can get into it.

SOLUTION

---
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: {}
-- yivo
kubernetes

1 Answer

3/12/2019

for this situation you can use Network policy to restrict access to foo

kind: NetworkPolicy

apiVersion: networking.k8s.io/v1

metadata:

  name: access-nginx

spec:

  podSelector:

    matchLabels:

      app: foo

  ingress:

  - from:

    - podSelector:

        matchLabels:

          app: bar
-- Semah Mhamdi
Source: StackOverflow