1. Answers
  2. Testing Kubernetes Pod Resilience by Injecting CPU/Memory Stress

How do I test Kubernetes pod resilience by injecting CPU/memory stress?

To test the resilience of Kubernetes pods by injecting CPU and memory stress, you can use a tool like stress-ng within a Kubernetes pod. This example demonstrates how to create a Kubernetes pod that runs stress-ng to simulate high CPU and memory usage.

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

// Define the Kubernetes namespace
const namespace = new k8s.core.v1.Namespace("stress-test-namespace", {
    metadata: { name: "stress-test" },
});

// Define the Kubernetes pod
const stressPod = new k8s.core.v1.Pod("stress-ng-pod", {
    metadata: {
        namespace: namespace.metadata.name,
        name: "stress-ng",
    },
    spec: {
        containers: [
            {
                name: "stress-ng",
                image: "alpine:latest", // Using alpine for a lightweight base image
                command: ["sh", "-c", "apk add --no-cache stress-ng && stress-ng --cpu 4 --vm 2 --vm-bytes 128M --timeout 60s"],
                resources: {
                    limits: {
                        cpu: "500m",
                        memory: "256Mi",
                    },
                    requests: {
                        cpu: "250m",
                        memory: "128Mi",
                    },
                },
            },
        ],
        restartPolicy: "Never",
    },
});

// Export the namespace and pod name
export const namespaceName = namespace.metadata.name;
export const podName = stressPod.metadata.name;

This Pulumi program does the following:

  1. Creates a Kubernetes namespace: The namespace stress-test is created to isolate the resources related to the stress test.
  2. Defines a Kubernetes pod: The pod named stress-ng is defined within the stress-test namespace. It uses the alpine:latest image and installs stress-ng to simulate CPU and memory stress.
  3. Configures the container: The container runs the stress-ng command to stress 4 CPU cores and 2 memory workers with 128MB each for a duration of 60 seconds. Resource limits and requests are set to manage the container’s resource usage.
  4. Exports the namespace and pod name: The namespace and pod name are exported for reference.

In conclusion, this program sets up a Kubernetes pod to test resilience by injecting CPU and memory stress using stress-ng. This can help you understand how your application behaves under high resource usage conditions.

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