How do I define custom load balancing policies for Kubernetes services?
In this guide, we will define custom load balancing policies for Kubernetes services using Pulumi. We will create a Kubernetes service and specify custom load balancing settings to control how traffic is distributed among the pods.
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Define a Kubernetes namespace
const namespace = new k8s.core.v1.Namespace("custom-lb-namespace", {
metadata: {
name: "custom-lb-namespace",
},
});
// Define a Kubernetes Deployment
const appLabels = { app: "my-app" };
const deployment = new k8s.apps.v1.Deployment("my-app-deployment", {
metadata: {
namespace: namespace.metadata.name,
},
spec: {
selector: { matchLabels: appLabels },
replicas: 2,
template: {
metadata: { labels: appLabels },
spec: {
containers: [{
name: "my-app",
image: "nginx",
ports: [{ containerPort: 80 }],
}],
},
},
},
});
// Define a Kubernetes Service with custom load balancing policy
const service = new k8s.core.v1.Service("my-app-service", {
metadata: {
namespace: namespace.metadata.name,
},
spec: {
type: "LoadBalancer",
selector: appLabels,
ports: [{ port: 80, targetPort: 80 }],
// Custom load balancing policy
sessionAffinity: "ClientIP", // Ensures requests from the same client are directed to the same pod
externalTrafficPolicy: "Local", // Preserves the client source IP
},
});
// Export the service's external IP
export const serviceIP = service.status.loadBalancer.ingress[0].ip;
Key Points
- Namespace Creation: We start by creating a Kubernetes namespace to organize our resources.
- Deployment Definition: We define a deployment for our application, specifying the number of replicas and the container details.
- Service with Custom Load Balancing: We create a Kubernetes service with a custom load balancing policy, including
sessionAffinity
set to “ClientIP” to ensure sticky sessions andexternalTrafficPolicy
set to “Local” to preserve the client source IP. - Exporting Service IP: We export the external IP of the service for easy access.
Summary
In this guide, we defined custom load balancing policies for a Kubernetes service using Pulumi. We created a namespace, a deployment, and a service with specific load balancing settings to control traffic distribution among the pods. The service was configured to maintain client session affinity and preserve the client source IP.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.