<p>I have a service sitting on the edge. This service needs to send some stuff somewhere over the Internet.</p>

<p>I'm using Canal CNI.</p>

<p>Can I define a NetworkPolicy that allows egress <em>only</em> to the internet, and not the rest of the cluster?</p>

<p>Something like the following would work:</p>

<pre><code>kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: only-allow-internet
spec:
  policyTypes:
    - Egress
  # match all pods in the namespace
  podSelector: {}
  egress:
    - to:
        - ipBlock:
            # allow all IPs
            cidr: 0.0.0.0/0
            except:
              # except the private IP ranges: https://en.wikipedia.org/wiki/Private_network
              - 10.0.0.0/8
              - 192.168.0.0/16
              - 172.16.0.0/20
</code></pre>

<p>It allows all IPs (since every IP matches <code>0.0.0.0/0</code>), except the private IP ranges that are defined by the IANA as private IP ranges.</p>

<p>Please note that this will break DNS lookups too, since by default kubernetes pods use the DNS server inside Kubernetes. You can verify it by running the following commands <strong>inside a pod</strong>:</p>

<pre><code>$ nslookup google.com
$ nslookup google.com 8.8.8.8
</code></pre>

<p>First one will time out, while second one will work.</p>

<p>By default, Kubernetes DNS IP would be <code>10.96.0.10</code>. You can verify it by checking <code>/etc/resolv.conf</code> inside a pod. Therefore, if you want DNS lookups to work, you might want to customize the <code>NetworkPolicy</code> further, define more specific IP ranges to allow DNS lookups.</p>

<p>Alternatively, you can define the DNS at the pod definition level. Details are here: <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-config" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-config</a></p>

<p>Additionally, instead of blocking all private IP ranges, you can only block the cluster pod/service ranges. You can find them out in the <code>kube-apiserver</code> parameters.</p>
