如何配置Kubernetes网络策略Ingress/Egress规则及Java库实现方法
Hey there! I see you're getting started with Kubernetes NetworkPolicies and need to implement specific rules using the Java client—let's walk through this step by step, focusing especially on that internet egress part you're stuck on.
First, a quick key reminder about Kubernetes NetworkPolicies: they operate on an allow-list basis. If you create a policy that targets specific pods, all traffic not explicitly allowed will be blocked. That simplifies some of your requirements automatically!
Prerequisites
First, make sure you're using a Kubernetes Java client that supports NetworkPolicies (the fabric8io client is the most widely used and well-documented). Add this dependency to your Maven project:
<dependency> <groupId>io.fabric8</groupId> <artifactId>kubernetes-client</artifactId> <version>6.10.0</version> <!-- Use the latest stable version from Maven Central --> </dependency>
Step-by-Step Rule Implementation
Let's build the policy to cover all your requirements:
1. Allow Ingress from Predefined IPs to Specific Ports
We'll explicitly allow only your list of trusted IPs to access the target port on your pods. Since NetworkPolicies block all unspecified ingress by default, this automatically covers your second requirement (denying private subnet ingress) unless your predefined IPs include private subnets (we'll handle that edge case in the code example).
2. Deny Ingress from Private Subnets
As noted, if your allowed IP list doesn't include any private subnets, the first rule already blocks them. If you do have private IPs in your allowed list but still want to block other private subnets, you can use the except clause in the IP block to exclude RFC 1918 private ranges.
3. Allow Egress to the Internet
This is the tricky part! To allow internet access, we target all IPs (0.0.0.0/0) but exclude the private RFC 1918 subnets. This way, pods can reach public internet IPs but can't communicate with private network ranges.
4. Deny Egress to Private Subnets
This is covered by the egress rule for internet access—since we're excluding private subnets from the allowed egress, those destinations are automatically blocked.
Full Java Code Example
Here's a complete implementation using the fabric8 client:
import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import java.util.List; public class AppNetworkPolicyCreator { public static void main(String[] args) { // Customize these values to match your environment String targetNamespace = "your-app-namespace"; List<String> allowedIngressIps = List.of("1.2.3.4/32", "5.6.7.8/32"); // Your trusted IPs String targetPort = "8080"; // Port to allow ingress on List<String> privateSubnets = List.of("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"); // RFC 1918 ranges try (KubernetesClient client = new DefaultKubernetesClient()) { // Build the NetworkPolicy object NetworkPolicy policy = new NetworkPolicyBuilder() .withNewMetadata() .withName("restrictive-app-policy") .withNamespace(targetNamespace) .endMetadata() .withNewSpec() // Apply this policy to pods with the label "app: your-app" .withPodSelector() .addToMatchLabels("app", "your-app") .endPodSelector() // Specify both Ingress and Egress policy types .withPolicyTypes(List.of("Ingress", "Egress")) // Ingress Rules: Allow only trusted IPs to access the target port .withIngress(List.of( new NetworkPolicyIngressRuleBuilder() .withFrom(allowedIngressIps.stream().map(ip -> new IPBlockBuilder() .withCidr(ip) // Optional: Uncomment to exclude private subnets if your allowed IPs include them //.withExcept(privateSubnets) .build() ).toList()) .withPorts(List.of( new NetworkPolicyPortBuilder() .withPort(targetPort) .withProtocol("TCP") .build() )) .build() )) // Egress Rules: Allow internet access, block private subnets .withEgress(List.of( new NetworkPolicyEgressRuleBuilder() .withTo(List.of( new IPBlockBuilder() .withCidr("0.0.0.0/0") // All IPs .withExcept(privateSubnets) // Exclude private ranges .build() )) // Allow all TCP/UDP ports to internet (adjust if you need restrictions) .withPorts(List.of( new NetworkPolicyPortBuilder().withProtocol("TCP").build(), new NetworkPolicyPortBuilder().withProtocol("UDP").build() )) .build() )) .endSpec() .build(); // Create the policy in your Kubernetes cluster client.networkPolicies().inNamespace(targetNamespace).create(policy); System.out.println("NetworkPolicy created successfully!"); } catch (Exception e) { System.err.println("Failed to create NetworkPolicy: " + e.getMessage()); e.printStackTrace(); } } }
Key Notes
- Pod Selector: Make sure the
matchLabelsmatches the pods you want to apply this policy to. If you want it to apply to all pods in the namespace, leave the selector empty. - Network Plugin Support: Your cluster must use a network plugin that supports NetworkPolicies (like Calico, Cilium, or Weave Net). The default Kubernetes network plugin (kube-proxy) does not support NetworkPolicies.
- Testing: After creating the policy, test it thoroughly:
- Use
kubectl exec -it <pod-name> -- curl <public-ip>to verify internet access works. - Try to access the pod from a private subnet IP to confirm it's blocked.
- Use
kubectl describe networkpolicy restrictive-app-policy -n your-app-namespaceto check the applied rules.
- Use
- Port Restrictions: If you only need to allow specific ports for internet egress (e.g., 80/443 for HTTP/HTTPS), replace the generic TCP/UDP ports with specific port numbers.
内容的提问来源于stack exchange,提问作者Kemal Taskiran

