Blocking All Ingress Traffic to the Database Pod
To begin, we block all incoming traffic to the database pod. This is achieved by creating a network policy that targets the database pod using labels and selectors. In our example, the database pod is labeledrole: db. The following YAML file defines a policy that denies all ingress traffic by default since no specific ingress rules are provided:
If no ingress rules are specified, Kubernetes treats the policy as a complete
block for incoming traffic.
Allowing Ingress Traffic from the API Pod
The next step is to allow ingress traffic from the API pod on port 3306. Because responses to permitted traffic are automatically allowed, configuring an ingress rule is sufficient. In this rule, the source is defined by pod selectors (and optionally namespace selectors) while the destination port is specified. For instance, to allow traffic only from pods labeledname: api-pod within namespaces labeled prod—and also permit traffic from a backup server with IP 192.168.5.10—update the network policy as follows:
from section restricts traffic to API pods in the production namespace (an AND condition). The second entry allows an external backup server by specifying its IP block.
Combining pod selectors with namespace selectors ensures that the rule applies
only to the intended pods within the correct namespace.
Configuring Egress Traffic
In scenarios where the database pod must initiate outbound connections (for example, sending backups to an external server), an egress rule becomes necessary. To support both ingress and egress traffic, includeEgress in the policyTypes and specify an egress rule.
The revised policy below permits the database pod to send traffic to a backup server at IP 192.168.5.10 on port 80 while still restricting all other outbound connections:
Ensure that your egress rules cover all required outbound connections. Missing
an egress rule may inadvertently block critical communication between your
services.
Summary of Network Policy Configuration
Experiment in your lab environment with these network policy configurations to gain hands-on experience with Kubernetes security practices. Understanding how selectors and rule ordering interact in your network policies will help you optimize traffic flow and maintain a secure architecture.
For additional resources on Kubernetes networking and security, visit the following links:
Happy networking, and see you in the next article!