Allow only one pod to access the nginx server
lab10server
restricted
default
sleepbox1
Create the restricted namespace.
kubectl create namespace restricted
Verify that the namespace was created successfully.
kubectl get ns
Run a webserver with the name lab10server in Namespace restricted, using the Nginx image and ensure it is exposed by a Service.
kubectl create deployment lab10server --image=nginx -n restricted
verify
kubectl get all -n restricted
kubectl expose deployment lab10server --port=80 --target-port=80 -n restricted
verfiy
kubectl get svc -n restricted
kubectl run sleepybox1 --image=busybox --restart=Never -- sleep 3600
kubectl get pod sleepybox1
Get service name:
Test from sleepybox1:
kubectl exec sleepybox1 -- wget -qO- lab10server.restricted
Test from sleepybox2:
kubectl exec sleepybox2 -- wget -qO- lab10server.restricted
NetworkPolicies work best with labels.
Label sleepybox1:
kubectl label pod sleepybox1 access=allowed
Verify:
kubectl get pods --show-labels
vim networkpolicy.yaml
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-sleepybox1 namespace: restricted spec: podSelector: {} policyTypes: - Ingress ingress: - from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: default podSelector: matchLabels: access: allowed
paste:
Understanding the YAML
This means:
kubectl apply -f networkpolicy.yaml
kubectl exec sleepybox1 -- wget -qO- --timeout=2 lab10server.restricted
should be successful with sleepybox1 - Expected sleepbox2 β Timeout / connection failure
access=allowed
podSelector: matchLabels: app: nginx
Protects the nginx server pod.
namespaceSelector: matchLabels: kubernetes.io/metadata.name: default
Traffic must come from the default namespace.
podSelector: matchLabels: access: allowed
Traffic must come from pods explicitly labeled access=allowed.
Whenever you see a NetworkPolicy question, draw:
SOURCE -----------> DESTINATION
sleepbox1 --------> lab10server β sleepybox2 -------> lab10server β
Then answer:
Build the NetworkPolicy from those answers.