<p>How can I define my networkpolicy so that both pods (test-server and test-server2) that are in the same namespace are reachable from outside the cluster but cannot reach each other?</p>
<pre><code>$ kubectl get pods
NAME                               READY   STATUS    RESTARTS   AGE
test-server-7555d49f48-sfzv9        1/1     Running   0          63m
test-server2-55c9cc78d4-knn59       1/1     Running   0          100m
</code></pre>
<pre><code># test: deny all ingress traffic
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: deny-all-ingress
spec:
  podSelector: {}
  policyTypes:
  - Ingress
</code></pre>
<pre><code># test: allow ingress traffic for test-server service
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-test-server-ingress
spec:
  podSelector:
    matchLabels:
      app: test-server
  policyTypes:
  - Ingress
  ingress:
  - {}

---
# test: allow ingress traffic for test-server2 service
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-test-server2-ingress
spec:
  podSelector:
    matchLabels:
      app: test-server2
  policyTypes:
  - Ingress
  ingress:
  - {}
</code></pre>
<p>Using this approach both services can be accessed externally, but you can also jump from one service to the other.</p>

<blockquote>
<p>How can I define my <code>network policy</code> so that both pods (test-server and test-server2) that are in the same namespace are reachable from outside the cluster but cannot reach each other?</p>
</blockquote>
<p>Your <code>NetworkPolicy</code> should be something similar to this one, based upon your settings</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: codewizard-block-policy
  namespace: codewizard
spec:
  # You can also add podSelection to 
  # be more specific.... (up to you)
  podSelector: {}

  policyTypes:
  - Ingress
  - Egress

  ingress:
  - from:
    # Block all traffic from the same subnet (10.10.10.10)
    # Or change the rule to only block a given IP and not a subnet
    - ipBlock:
        cidr: 10.10.10.10/32
        except:
        - 172.17.0.0/16 
    # Add allow ip from your LoadBalancer IP
  
  # Same thing for out going traffic
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 172.17.0.0/16
</code></pre>
<hr />
<ul>
<li>Another solution might be to use <code>Ingress</code> with the following annotation:
<code>ingress.kubernetes.io/whitelist-source-range: &quot;x.x.x.x/xx&quot;</code></li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: whitelist
  annotations:
    ingress.kubernetes.io/whitelist-source-range: &quot;1.1.1.1/24&quot;
spec:
  rules:
  - host: whitelist.test.net
  http:
    paths:
    - path: /
    backend:
      serviceName: webserver
     servicePort: 80
</code></pre>
