Prerequisites:

  1. Download the Cilium CLI (https://cilium.io/):
curl -L --remote-name-all <https://github.com/cilium/cilium-cli/releases/latest/download/cilium-linux-amd64.tar.gz{,.sha256sum}>
sha256sum --check cilium-linux-amd64.tar.gz.sha256sum
sudo tar xzvfC cilium-linux-amd64.tar.gz /usr/local/bin
rm cilium-linux-amd64.tar.gz{,.sha256sum}
  1. Install Cilium:
cilium install

If using GKE, Cilium CLI will automatically detect the cluster, install everything and restart any running Pods.

To validate installation is successful, run cilium status --wait (this might take a couple of minutes to run).

Let's look at an example that demonstrates how to disable egress traffic from the Pods.

apiVersion: v1
kind: Pod
metadata:
  name: no-egress-pod
  labels:
    app.kubernetes.io/name: hello
spec:
  containers:
    - name: container
      image: radial/busyboxplus:curl
      command: ["sh", "-c", "sleep 3600"]

Save the above YAML to no-egress-pod.yaml and create the Pod using kubectl apply -f no-egress-pod.yaml.

Once the Pod is running, let's try calling google.com using curl:

$ kubectl exec -it no-egress-pod -- curl -I -L google.com
HTTP/1.1 301 Moved Permanently
Location: <http://www.google.com/>
Content-Type: text/html; charset=UTF-8
Date: Fri, 18 Jun 2021 19:44:50 GMT
Expires: Sun, 18 Jul 2021 19:44:50 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN

HTTP/1.1 200 OK
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Date: Fri, 18 Jun 2021 19:44:50 GMT
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Expires: Fri, 18 Jun 2021 19:44:50 GMT
Cache-Control: private
Set-Cookie: 1P_JAR=2021-06-18-19; expires=Sun, 18-Jul-2021 19:44:50 GMT; path=/; domain=.google.com; Secure
Set-Cookie: NID=217=pMup-tcDTNi2hwt7-d8t7rwmP_BVV8FDbDSustRh9e5bnO5lmKcFZq_L8hFW74vV_ZYU9-SIetTaZmBxeSCTDpV3u4b7pryB9tJm_E4-tsUpD7KCTzLKay4mIwc-BwfWfN8WS4Jkw1PJaPfoTjKxr-LXr36RkXBXnxiyiHtV1fk; expires=Sat, 18-Dec-2021 19:44:50 GMT; path=/; domain=.google.com; HttpOnly

The call completes successfully. Let's define a network policy that will prevent egress for Pods with the label app.kubernetes.io/name: hello:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-egress
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: hello
  policyTypes:
    - Egress

If you run the same command this time, curl won't be able to resolve the host:

$ kubectl exec -it no-egress-pod -- curl -I -L google.com
curl: (6) Couldn't resolve host 'google.com'

Try running kubectl edit pod no-egress-pod and change the label value to hello123. Save the changes and then re-run the curl command. This time, the command works fine because we changed the Pod label, and the network policy does not apply to it anymore.