<p>I have a namespace with three pods (deployments) <code>app01</code>, <code>app02</code>, and <code>db</code>. <code>db</code> is exposed within the cluster via a <code>ClusterIP</code> service with name <code>dbsvc</code>. I connect to the service from <code>app01</code> and <code>app02</code> using the cluster DNS like <code>dbsvc.namespace.svc.cluster.local</code>. However, I do not want anyone to access <code>dbsvc</code> from outside my namespace. (Since it's ClusterIP, it's not going to be accessible outside the cluster anyways).</p>
<p>In other words, I want to restrict access to <code>dbsvc.namespace.svc.cluster.local</code> only from <code>app01</code> and <code>app02</code>.</p>
<p>How do I achieve this?</p>

Rajshri Mohan K S
<p>Network traffic can be restricted with a <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/" rel="nofollow noreferrer">Network Policy</a> on a cluster using a <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/" rel="nofollow noreferrer">network plugin</a> (CNI) that supports them, like <a href="https://www.projectcalico.org/" rel="nofollow noreferrer">calico</a>.</p>
<p>The policy selectors are deployment specific so here are some example values:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app-network-policy
  namespace: namespace
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          project: myproject
    - podSelector:
        matchLabels:
          role: app
    ports:
    - protocol: TCP
      port: 3306
</code></pre>
