<p>I have a pod (<code>kubectl run app1 --image tomcat:7.0-slim</code>) in GKE after applying the egress network policy <code>apt-get update</code> command unable to connect internet.</p>
<p><em><strong>Before applying policy:</strong></em></p>
<p><a href="https://i.stack.imgur.com/8et61.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8et61.png" alt="enter image description here" /></a></p>
<p><em><strong>After applying policy:</strong></em></p>
<p><a href="https://i.stack.imgur.com/u4Dxd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u4Dxd.png" alt="enter image description here" /></a></p>
<p><em><strong>This is the policy applied:</strong></em></p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app2-np
  namespace: default
spec:
  podSelector:
    matchLabels:
      name: app2
  policyTypes:
  - Egress
  - Ingress
  ingress:
  - {}
  egress:
  - to:
    - podSelector:
        matchLabels:
          name: app3
    ports:
    - port: 8080

  - ports:
    - port: 80
    - port: 53
    - port: 443
</code></pre>
<p>The Here am able to connect 8080 port of app3 pod in same namespace. Please help in correcting my netpol.</p>

<p>It happens because you are defining the egress rule only for app3 on port 8080, and it will block all internet connect attempts.</p>
<p>If you need to use access internet from some of your pods, you can tag them and create a NetworkPOlicy to permit the internet access.</p>
<p>In the example below, the pods with the tag <code>networking/allow-internet-egress: &quot;true&quot;</code> will be able to reach the internet:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: internet-egress
spec:
  podSelector:
    matchLabels:
      networking/allow-internet-egress: &quot;true&quot;
  egress:
  - {}
  policyTypes:
  - Egress
</code></pre>
<p>Another option is allow by ip blocks, in the example below, a rule will allow the internet access (<code>0.0.0.0</code>) <strong>except</strong> for the ipBlocks <code>10.0.0.0/8</code></p>
<pre><code>kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-internet-only
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
      - ipBlock:
        cidr: 0.0.0.0/0
          except:
            - 10.0.0.0/8
</code></pre>
<p>Finally, in <a href="https://orca.tufin.io/netpol/" rel="nofollow noreferrer">this</a> site you can visualize your NetworkPolices in a good way to understand what is the exact behaviour.</p>
<p>References:</p>
<p><a href="https://www.stackrox.com/post/2020/01/kubernetes-egress-network-policies/" rel="nofollow noreferrer">https://www.stackrox.com/post/2020/01/kubernetes-egress-network-policies/</a></p>
<p><a href="https://stackoverflow.com/questions/57789969/kubernets-networkpolicy-allow-external-traffic-to-internet-only">Kubernets networkpolicy allow external traffic to internet only</a></p>
