Skip to content

Instantly share code, notes, and snippets.

@fragaLY
Created December 24, 2021 14:48
Show Gist options
  • Save fragaLY/1db7a0b5045f5154d10a03f4621caa2a to your computer and use it in GitHub Desktop.
Save fragaLY/1db7a0b5045f5154d10a03f4621caa2a to your computer and use it in GitHub Desktop.
Create a cluster network policy
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: foo-allow-to-hello
spec:
policyTypes:
- Egress
podSelector:
matchLabels:
app: foo
egress:
- to:
- podSelector:
matchLabels:
app: hello
- to:
ports:
- protocol: UDP
port: 53
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: hello-allow-from-foo
spec:
policyTypes:
- Ingress
podSelector:
matchLabels:
app: hello
ingress:
- from:
- podSelector:
matchLabels:
app: foo
#preset
export my_zone=us-central1-a
export my_cluster=standard-cluster-1
source <(kubectl completion bash)
git clone https://github.com/GoogleCloudPlatform/training-data-analyst
ln -s ~/training-data-analyst/courses/ak8s/v1.1 ~/ak8s
cd ~/ak8s/GKE_Networks/
#setup cluster
gcloud container clusters create $my_cluster --num-nodes 3 --enable-ip-alias --zone $my_zone --enable-network-policy
gcloud container clusters get-credentials $my_cluster --zone $my_zone
kubectl run hello-web --labels app=hello --image=gcr.io/google-samples/hello-app:1.0 --port 8080 --expose
kubectl apply -f hello-allow-from-foo.yaml
kubectl get networkpolicy
#validate the ingress policy
kubectl run test-1 --labels app=foo --image=alpine --restart=Never --rm --stdin --tty
wget -qO- --timeout=2 http://hello-web:8080
kubectl run test-1 --labels app=other --image=alpine --restart=Never --rm --stdin --tty
wget -qO- --timeout=2 http://hello-web:8080
#restrict outgoing traffic from the Pods
kubectl apply -f foo-allow-to-hello.yaml
kubectl get networkpolicy
kubectl run hello-web-2 --labels app=hello-2 --image=gcr.io/google-samples/hello-app:1.0 --port 8080 --expose
kubectl run test-3 --labels app=foo --image=alpine --restart=Never --rm --stdin --tty
wget -qO- --timeout=2 http://hello-web:8080
wget -qO- --timeout=2 http://www.example.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment