kubectl create namespace restricted kubectl create namespace access
Verify:
kubectl get ns
Create the web server in the restricted namespace.
kubectl run lab156web \ --image=nginx \ --namespace=restricted \ --port=80
Verify:
kubectl get pods -n restricted
Create a BusyBox pod in the access namespace with the required label.
kubectl run lab156access \ --image=busybox \ --namespace=access \ --labels=access=true \ --restart=Never \ -- sleep 3600
Verify labels:
kubectl get pods -n access --show-labels
Create the file restricted-policy.yaml.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-access-port-80
namespace: restricted
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: access
podSelector:
matchLabels:
access: "true"
ports:
- protocol: TCP
port: 80
Apply the policy:
kubectl apply -f restricted-policy.yaml
Check that the policy exists:
kubectl get netpol -n restricted kubectl describe netpol allow-access-port-80 -n restricted
Expected output:
NamespaceSelector: kubernetes.io/metadata.name=access PodSelector: access=true Port: 80/TCP
kubectl create ns restricted kubectl create ns access kubectl run lab156web \ --image=nginx \ -n restricted \ --port=80 kubectl run lab156access \ --image=busybox \ -n access \ --labels=access=true \ --restart=Never \ -- sleep 3600