Installing network policies.
kubernetes security networking
Network Policy support
Network policies are a highly recommended, although sometimes confusing, security control. You can see network policies as a micro-firewall, that denies or allows traffic at the pod or namespace level.
- Network policies work using labels and namespaces to select resources (pods) for which they apply.
- Network policies use the pod’s IP and port. You should not configure network policies using a service labels and/or the port. Use a service endpoints (
kubectl get endpoint <my-service>
) instead.
Network policies can be installed using kubectl apply
, like any other resource within Kubernetes.
kubectl get networkpolicies
- list network policies within your current namespacekubectl get networkpolicies -A
- list all network policies within the clusterkubectl describe networkpolicies <policy>
- view a summary of the network policy
Recommended network policies
Default deny
This network policy should be installed in any namespace in your cluster. It will deny any network traffic for any pod running within the namespace this network policy is installed in.
This includes;
- traffic between pods within the same namespace
- traffic between pods in other namespaces
- traffic to any external service (e.g. private IP ranges, public internet, etc)
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: default-deny-all
namespace: mynamespace
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
ingress: []
egress: []
Allow DNS traffic
Allow DNS traffic from your pod to the kube-system namespace. This is where the in cluster DNS resolver runs (CoreDNS).
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: allow-egress-dns
namespace: mynamespace
spec:
podSelector:
matchLabels: {}
policyTypes:
- Egress
egress:
- ports:
# Allow DNS
- port: 53
protocol: UDP
- port: 53
protocol: TCP
to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
Allow ingress from ingress-controller
Be explicit when installing a policy that allows ingress traffic from anywhere. This means listing the ports to which this traffic is allowed.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: allow-traffic-from-ingress
namespace: mynamespace
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: example
app.kubernetes.io/instance: example-instance
policyTypes:
- Ingress
ingress:
- ports:
- port: 8000
from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: 'ingress-nginx'
The above policy allows any tcp traffic on poort 8000
from the namespace ingress-nginx
.