1. Answers
  2. Restricting external egress traffic with an egress NetworkPolicy

How do I restrict external egress traffic with an egress NetworkPolicy?

In this guide, we will create a Kubernetes NetworkPolicy to restrict external egress traffic. NetworkPolicies are used to control the communication between pods and other network endpoints. By defining an egress NetworkPolicy, we can specify which external destinations the pods in a namespace are allowed to communicate with.

Key Points:

  • We will create a Kubernetes namespace.
  • We will define a NetworkPolicy that restricts egress traffic.
  • The policy will allow traffic only to specific IP addresses or CIDR blocks.
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Create a namespace
const namespace = new k8s.core.v1.Namespace("example-namespace", {
    metadata: {
        name: "example-namespace",
    },
});

// Define a NetworkPolicy to restrict egress traffic
const egressNetworkPolicy = new k8s.networking.v1.NetworkPolicy("egress-policy", {
    metadata: {
        namespace: namespace.metadata.name,
        name: "egress-policy",
    },
    spec: {
        podSelector: {}, // Apply to all pods in the namespace
        policyTypes: ["Egress"],
        egress: [
            {
                to: [
                    {
                        ipBlock: {
                            cidr: "192.168.0.0/16", // Allow traffic to this CIDR block
                        },
                    },
                    {
                        ipBlock: {
                            cidr: "10.0.0.0/8",
                            except: ["10.1.0.0/16"], // Allow traffic to this CIDR block except the specified range
                        },
                    },
                ],
                ports: [
                    {
                        protocol: "TCP",
                        port: 80, // Allow HTTP traffic
                    },
                    {
                        protocol: "TCP",
                        port: 443, // Allow HTTPS traffic
                    },
                ],
            },
        ],
    },
});

export const namespaceName = namespace.metadata.name;
export const networkPolicyName = egressNetworkPolicy.metadata.name;

Summary:

In this guide, we created a Kubernetes NetworkPolicy to restrict external egress traffic. The policy allows egress traffic only to specific IP addresses or CIDR blocks and only on specified ports (HTTP and HTTPS). This helps in securing the communication from the pods to the external network.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up