This tutorial aims to guide you through the process of configuring network policies in Kubernetes. Network policies are Kubernetes resources that control the traffic between pods and network endpoints.
By the end of this tutorial, you will be able to:
- Understand what Kubernetes Network Policies are.
- Configure network policies in Kubernetes.
- Implement best practices when dealing with network policies.
Before starting this tutorial, it is recommended to have:
- Basic knowledge of Kubernetes.
- A running Kubernetes cluster. If you don't have one, you can set up a local cluster using Minikube.
Network policies are rules that govern how pods communicate with each other and other network endpoints. They use labels to select pods and define rules which specify what traffic is allowed to the selected pods.
To create a Network Policy, you need to create a YAML file that defines the policy, then apply it using kubectl
.
Here is an example of a basic network policy:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
- ipBlock:
cidr: 172.17.0.0/16
except:
- 172.17.1.0/24
ports:
- protocol: TCP
port: 6379
This policy allows traffic from the IP range 172.17.0.0/16, excluding 172.17.1.0/24, to access pods with the label role=db
on TCP port 6379.
This is a simple network policy that allows all incoming traffic to all pods in a namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
ingress:
- {}
In the above YAML:
- podSelector: {}
selects all pods in the namespace.
- ingress: - {}
allows all incoming traffic.
This network policy denies all incoming traffic to all pods in a namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
ingress: []
In the above YAML:
- podSelector: {}
selects all pods in the namespace.
- ingress: []
denies all incoming traffic as no ingress rules are defined.
In this tutorial, you have learned about Kubernetes Network Policies and how to configure them. You've seen how to create a basic network policy, and how to allow or deny all incoming traffic.
For further learning, you can explore:
- How to configure egress rules in network policies.
- How to combine multiple rules in a single network policy.
Create a network policy that allows traffic only from pods with the label app=frontend
to pods with the label app=backend
.
Create a network policy that denies all incoming traffic to a pod with the label app=secure
, except from pods with the label app=trusted
.
Remember, practicing with real examples helps to solidify your understanding and gain hands-on experience.