kubectl create namespace restricted
kubectl get ns
kubectl run lab10server -n restricted --image=nginx
kubectl expose pod lab10server -n restricted --port=80
kubectl run sleepybox1 --image=busybox -- sleep 3600 kubectl run sleepybox2 --image=busybox -- sleep 3600
Label the namespace and sleepybox1.
kubectl label ns default project=myproject kubectl label pod sleepybox1 role=access
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: restricted
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
project: myproject
podSelector:
matchLabels:
role: access
kubectl apply -f networkpolicy.yaml
kubectl get netpol -n restricted
sleepybox1 should work:
kubectl exec sleepybox1 -- wget -qO- --timeout=2 lab10server.restricted
sleepybox2 should fail:
kubectl exec sleepybox2 -- wget -qO- --timeout=2 lab10server.restricted
- namespaceSelector podSelectorMeans: Namespace AND Pod
- namespaceSelector - podSelectorMeans: Namespace OR Pod
During the lab, both of the following commands successfully reached the nginx web server:
kubectl exec sleepybox1 -- wget -qO- lab10server.restricted kubectl exec sleepybox1 -- wget -qO- lab10server.restricted.svc.cluster.local
This happens because Kubernetes automatically creates DNS records for Services.
lab10server.restricted.svc.cluster.local
Kubernetes uses the following format for Service DNS entries:
<service-name>.<namespace>.svc.cluster.local
For this lab:
Service Name: lab10server Namespace: restricted DNS Name: lab10server.restricted.svc.cluster.local
Pods automatically receive DNS search domains. Kubernetes will try to resolve shorter names into the full DNS name.
Therefore:
lab10server.restricted
automatically expands to:
lab10server.restricted.svc.cluster.local
behind the scenes.
You can view the DNS search domains configured for a pod:
kubectl exec sleepybox1 -- cat /etc/resolv.conf
Example output:
search default.svc.cluster.local svc.cluster.local cluster.local
lab10server
lab10server.restricted
lab10server.restricted.svc.cluster.local
lab10server.restrictedbecause it is shorter and easier to type, but both names resolve to the same Kubernetes Service.
default has label project=myprojectsleepybox1 has label role=accessrole=access label.
This demonstrates how NetworkPolicies can combine
namespaceSelector and
podSelector using AND logic.
Instead of downloading the entire nginx page, we can simply test
connectivity using wget --spider.
kubectl exec -it sleepybox1 -- \ wget --spider --timeout=1 \ lab10server.restricted.svc.cluster.local
Expected output:
Connecting to lab10server.restricted.svc.cluster.local (10.100.138.249:80) remote file exists
The --spider option checks whether the resource is
reachable without downloading the web page.
If the NetworkPolicy blocks the connection, the command should time out instead of returning remote file exists.