In Kubernetes, network policies are a powerful feature that allow you to control the traffic flow between pods within your cluster. By using network policies, you can define rules that specify which pods can communicate with each other and how they can do so. This tutorial will guide you through implementing network policies to secure your Kubernetes applications.
Network policies in Kubernetes are defined as YAML files that specify a set of rules for traffic flow between pods. These rules include:
Network policies are enforced by network plugins that support them, such as Calico, Cilium, and Weave Net. These plugins intercept traffic at the network layer and enforce the rules defined in your policies.
Let's start with a basic example where we restrict access to a database pod so that only a specific application pod can communicate with it.
First, create a pod that acts as a database:
1apiVersion: v12kind: Pod3metadata:4name: db-pod5labels:6app: db7spec:8containers:9- name: db-container10image: postgres
Apply this configuration using the following command:
Now, create a network policy that restricts access to the database pod so that only the application pod can communicate with it:
1apiVersion: networking.k8s.io/v12kind: NetworkPolicy3metadata:4name: db-policy5spec:6podSelector:7matchLabels:8app: db9policyTypes:10- Ingress11ingress:12- from:13- podSelector:14matchLabels:15app: app
Apply this configuration using the following command:
Then, try to ping the database pod:
Exec into the test pod:
You should not receive any response, indicating that the connection is blocked by the network policy.
In this tutorial, you learned how to implement basic network policies to control traffic flow between pods in Kubernetes. For more advanced use cases, such as managing egress rules or using multiple selectors, refer to the Kubernetes documentation.
If you're interested in automating and managing your Kubernetes resources, consider exploring Helm for Package Management. Helm allows you to package, deploy, and manage Kubernetes applications with ease.