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
| Configuration Aspect | Description | YAML Reference |
|---|---|---|
| Blocking Traffic | Deny all ingress traffic to the database pod by default. | Initial policy with podSelector for role: db. |
| Allowing Ingress | Permit API pod access on port 3306 by combining pod and namespace selectors. Also allow a specific external IP. | Ingress rule with pod and namespace selectors plus ipBlock. |
| Configuring Egress | Enable the database pod to send outbound traffic to an external backup server on port 80. | Egress rule addition with ipBlock for backup server. |