<p>I'm setting up a namespace in my kubernetes cluster to deny any outgoing network calls like <a href="http://company.com" rel="nofollow noreferrer">http://company.com</a> but to allow inter pod communication within my namespace like <a href="http://my-nginx" rel="nofollow noreferrer">http://my-nginx</a> where my-nginx is a kubernetes service pointing to my nginx pod.</p>

<p>How to achieve this using network policy. Below network policy helps in blocking all outgoing network calls </p>

<pre><code>kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: deny-all-egress
  namespace: sample
spec:
  policyTypes:
  - Egress
  podSelector: {}
</code></pre>

<p>How to white list only the inter pod calls?</p>

Pradeep
<p>Using Network Policies you can whitelist all pods in a namespace:</p>

<pre><code>kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-egress-to-sample
  namespace: sample
spec:
  policyTypes:
  - Egress
  podSelector: {}
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: sample
</code></pre>

<p>As you probably already know, pods with at least one Network Policy applied to them can only communicate to targets allowed by any Network Policy applied to them.</p>

<p>Names don't actually matter. Selectors (namespaceSelector and podSelector in this case) only care about labels. Labels are key-value pairs associated with resources. The above example assumes the namespace called <code>sample</code> has a label of <code>name=sample</code>.</p>

<p>If you want to whitelist the namespace called <code>http://my-nginx</code>, first you need to add a label to your namespace (if it doesn't already have one). <code>name</code> is a good key IMO, and the value can be the name of the service, <code>http://my-nginx</code> in this particular case (not sure if <code>:</code> and <code>/</code> can be a part of a label though). Then, just using this in your Network Policies will allow you to target the namespace (either for ingress or egress)</p>

<pre><code>    - namespaceSelector:
        matchLabels:
          name: http://my-nginx
</code></pre>

<p>If you want to allow communication to a service called <code>my-nginx</code>, the service's name doesn't really matter. You need to select the target pods using podSelector, which should be done with the same label that the service uses to know which pods belong to it. Check your service to get the label, and use the <code>key: value</code> in the Network Policy. For example, for a key=value pair of role=nginx you should use</p>

<pre><code>    - podSelector:
        matchLabels:
          role: nginx
</code></pre>
