<p>I have the following service:</p>

<pre><code>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
</code></pre>

<p>This service point to the following deployment:</p>

<pre><code>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
</code></pre>

<p>I also have another deployment:</p>

<pre><code>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
</code></pre>

<p><code>foo</code> is deployed to Kubernetes namespace called <code>kube-protected</code>, <code>bar</code> is deployed to default Kubernetes namespace.</p>

<p><code>foo</code> contains import data and should be well secured. </p>

<p>Kubernetes default namespace may also contain another deployments: <code>qux</code>, <code>baz</code>, etc.</p>

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

<p><strong>SOLUTION</strong></p>

<pre><code>---
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: {}
</code></pre>

yivo
<p>for this situation you can use Network policy to restrict access to <strong>foo</strong></p>

<pre><code>kind: NetworkPolicy

apiVersion: networking.k8s.io/v1

metadata:

  name: access-nginx

spec:

  podSelector:

    matchLabels:

      app: foo

  ingress:

  - from:

    - podSelector:

        matchLabels:

          app: bar
</code></pre>
