1. Answers
  2. Building a Kubernetes Autoscaler

How do I build a Kubernetes autoscaling horizontalpodautoscaler?

In this guide, we will create a Kubernetes Horizontal Pod Autoscaler (HPA) using Pulumi. The HPA automatically scales the number of pods in a deployment based on observed CPU utilization. This ensures that your application can handle varying levels of traffic efficiently.

Key Points

  • We will create a Kubernetes Deployment.
  • We will define a Horizontal Pod Autoscaler for the Deployment.
  • The HPA will scale the pods based on CPU utilization.

Below is the Pulumi program in TypeScript:

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Create a Kubernetes namespace
const ns = new k8s.core.v1.Namespace("app-ns");

// Create a Kubernetes Deployment
const appLabels = { app: "myapp" };
const deployment = new k8s.apps.v1.Deployment("myapp-deployment", {
    metadata: {
        namespace: ns.metadata.name,
    },
    spec: {
        selector: { matchLabels: appLabels },
        replicas: 1,
        template: {
            metadata: { labels: appLabels },
            spec: {
                containers: [{
                    name: "myapp",
                    image: "nginx",
                    resources: {
                        requests: {
                            cpu: "100m"
                        },
                        limits: {
                            cpu: "500m"
                        }
                    }
                }],
            },
        },
    },
});

// Create a Horizontal Pod Autoscaler
const hpa = new k8s.autoscaling.v2beta2.HorizontalPodAutoscaler("myapp-hpa", {
    metadata: {
        namespace: ns.metadata.name,
    },
    spec: {
        scaleTargetRef: {
            apiVersion: "apps/v1",
            kind: "Deployment",
            name: deployment.metadata.name,
        },
        minReplicas: 1,
        maxReplicas: 10,
        metrics: [{
            type: "Resource",
            resource: {
                name: "cpu",
                target: {
                    type: "Utilization",
                    averageUtilization: 50,
                },
            },
        }],
    },
});

Summary

In this guide, we created a Kubernetes namespace, a Deployment, and a Horizontal Pod Autoscaler using Pulumi. The HPA automatically scales the number of pods in the deployment based on CPU utilization, ensuring efficient resource usage and handling varying traffic loads.

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