Kubernetes Integration Testing with kind: Local Cluster Testing for CI/CD

Kubernetes Integration Testing with kind: Local Cluster Testing for CI/CD

kind (Kubernetes in Docker) runs a Kubernetes cluster inside Docker containers. It's the standard tool for running Kubernetes integration tests in CI — fast to spin up, cheap to run, and close enough to real Kubernetes to catch most issues.

This guide covers using kind for integration testing: cluster configuration, deploying applications, verifying behavior, and integrating kind into your CI pipeline.

Why kind Over minikube for CI

Both kind and minikube create local Kubernetes clusters. For CI, kind wins on three counts:

Speed: kind creates a cluster in 30-60 seconds. minikube is slower because it creates a VM.

Resource usage: kind runs directly in Docker with no hypervisor overhead.

Multi-cluster support: kind can run multiple named clusters simultaneously. You can test upgrade paths or multi-cluster scenarios without teardown.

For local development, minikube has better tooling (dashboard, addons). For CI, kind is the right choice.

Installing and Creating a Cluster

# Install kind
brew install kind  # macOS
# or
curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.22.0/kind-linux-amd64
chmod +x ./kind && mv ./kind /usr/local/bin/kind

# Create a basic cluster
kind create cluster --name test-cluster

# Verify
kubectl cluster-info --context kind-test-cluster

Configuring kind for Your Application

Most applications need more than the default single-node cluster. Configure kind with a multi-node setup that mirrors production:

# kind-config.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4

nodes:
  - role: control-plane
    kubeadmConfigPatches:
      - |
        kind: InitConfiguration
        nodeRegistration:
          kubeletExtraArgs:
            node-labels: "ingress-ready=true"
    extraPortMappings:
      - containerPort: 80
        hostPort: 80
        protocol: TCP
      - containerPort: 443
        hostPort: 443
        protocol: TCP

  - role: worker
  - role: worker

networking:
  apiServerPort: 6443
  podSubnet: "10.244.0.0/16"

# Pre-load images to avoid pulling in tests
# containerdConfigPatches:
#   - |-
#     [plugins."io.containerd.grpc.v1.cri".registry]
#       config_path = "/etc/containerd/certs.d"

Create the cluster:

kind create cluster --name integration-test --config kind-config.yaml

Loading Local Images Into kind

kind clusters can't pull from your local Docker registry. You need to load images explicitly:

# Build your image
docker build -t myapp:test .

# Load into kind
kind load docker-image myapp:test --name integration-test

# Verify
docker exec -it integration-test-control-plane crictl images | grep myapp

In CI, build the image and load it before running tests:

#!/bin/bash
# setup-kind.sh

KIND_CLUSTER="integration-test"

# Create cluster
kind create cluster --name $KIND_CLUSTER --config kind-config.yaml

# Build and load application images
docker build -t myapp:$GITHUB_SHA -f Dockerfile .
kind load docker-image myapp:$GITHUB_SHA --name $KIND_CLUSTER

# Deploy test dependencies (databases, message queues)
kubectl apply -f k8s/test-dependencies/ --context kind-$KIND_CLUSTER

# Wait for dependencies to be ready
kubectl wait --for=condition=ready pod \
  -l app=postgres \
  --timeout=120s \
  --context kind-$KIND_CLUSTER

Writing Kubernetes Integration Tests

Integration tests for Kubernetes verify that your application runs correctly in a cluster — not just that the container works. Use controller-runtime's envtest package for in-process tests, or deploy to kind and test via HTTP:

// integration_test.go
package integration

import (
    "context"
    "fmt"
    "net/http"
    "testing"
    "time"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
    appsv1 "k8s.io/api/apps/v1"
    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
)

func getClient(t *testing.T) *kubernetes.Clientset {
    t.Helper()
    config, err := clientcmd.BuildConfigFromFlags("", "~/.kube/config")
    require.NoError(t, err)
    client, err := kubernetes.NewForConfig(config)
    require.NoError(t, err)
    return client
}

func TestDeploymentRollsOut(t *testing.T) {
    ctx := context.Background()
    client := getClient(t)

    // Deploy the application
    deployment := &appsv1.Deployment{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "myapp",
            Namespace: "default",
        },
        Spec: appsv1.DeploymentSpec{
            Replicas: int32Ptr(2),
            Selector: &metav1.LabelSelector{
                MatchLabels: map[string]string{"app": "myapp"},
            },
            Template: corev1.PodTemplateSpec{
                ObjectMeta: metav1.ObjectMeta{
                    Labels: map[string]string{"app": "myapp"},
                },
                Spec: corev1.PodSpec{
                    Containers: []corev1.Container{{
                        Name:  "myapp",
                        Image: fmt.Sprintf("myapp:%s", testImageTag),
                        Ports: []corev1.ContainerPort{{ContainerPort: 8080}},
                    }},
                },
            },
        },
    }

    _, err := client.AppsV1().Deployments("default").Create(ctx, deployment, metav1.CreateOptions{})
    require.NoError(t, err)

    t.Cleanup(func() {
        client.AppsV1().Deployments("default").Delete(ctx, "myapp", metav1.DeleteOptions{})
    })

    // Wait for rollout
    require.NoError(t, waitForDeployment(ctx, client, "default", "myapp", 2*time.Minute))

    // Verify all replicas are ready
    dep, err := client.AppsV1().Deployments("default").Get(ctx, "myapp", metav1.GetOptions{})
    require.NoError(t, err)

    assert.Equal(t, int32(2), dep.Status.ReadyReplicas,
        "Expected 2 ready replicas, got %d", dep.Status.ReadyReplicas)
}

func waitForDeployment(ctx context.Context, client *kubernetes.Clientset, namespace, name string, timeout time.Duration) error {
    deadline := time.Now().Add(timeout)
    for time.Now().Before(deadline) {
        dep, err := client.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{})
        if err != nil {
            return err
        }
        if dep.Status.ReadyReplicas == *dep.Spec.Replicas {
            return nil
        }
        time.Sleep(2 * time.Second)
    }
    return fmt.Errorf("deployment %s not ready within %v", name, timeout)
}

func TestServiceIsAccessible(t *testing.T) {
    ctx := context.Background()
    client := getClient(t)

    // Port-forward to the service
    svc, err := client.CoreV1().Services("default").Get(ctx, "myapp", metav1.GetOptions{})
    require.NoError(t, err)
    require.NotEmpty(t, svc.Spec.Ports)

    // Use port-forward (simplified — in practice use kubectl port-forward subprocess)
    localPort := 18080
    // ... start port-forward ...

    // Test HTTP endpoint
    resp, err := http.Get(fmt.Sprintf("http://localhost:%d/health", localPort))
    require.NoError(t, err)
    defer resp.Body.Close()

    assert.Equal(t, 200, resp.StatusCode)
}

func int32Ptr(i int32) *int32 { return &i }

Testing With Kubetest2

For structured test orchestration with kind:

# Install kubetest2
go install sigs.k8s.io/kubetest2@latest
go install sigs.k8s.io/kubetest2/kubetest2-kind@latest

# Run tests
kubetest2 kind \
  --up \
  --down \
  --test=exec \
  -- go test ./integration/... -v

Using Ginkgo for BDD-Style Kubernetes Tests

Kubernetes' own testing framework uses Ginkgo. If your team uses it:

// suite_test.go
package integration_test

import (
    "testing"
    . "github.com/onsi/ginkgo/v2"
    . "github.com/onsi/gomega"
)

func TestIntegration(t *testing.T) {
    RegisterFailHandler(Fail)
    RunSpecs(t, "Integration Suite")
}

// deployment_test.go
var _ = Describe("Application deployment", func() {
    var ctx context.Context
    var client *kubernetes.Clientset

    BeforeEach(func() {
        ctx = context.Background()
        client = getClient(GinkgoT())
    })

    Describe("rolling update", func() {
        It("updates without downtime", func() {
            // Deploy v1
            createDeployment(ctx, client, "myapp:v1")

            // Verify v1 is running
            Eventually(func() int32 {
                dep, _ := client.AppsV1().Deployments("default").Get(ctx, "myapp", metav1.GetOptions{})
                return dep.Status.ReadyReplicas
            }, 2*time.Minute, 2*time.Second).Should(Equal(int32(2)))

            // Update to v2
            updateDeploymentImage(ctx, client, "myapp", "myapp:v2")

            // Verify v2 rolls out without errors
            Eventually(func() string {
                dep, _ := client.AppsV1().Deployments("default").Get(ctx, "myapp", metav1.GetOptions{})
                return dep.Spec.Template.Spec.Containers[0].Image
            }, 3*time.Minute, 2*time.Second).Should(Equal("myapp:v2"))
        })
    })
})

CI Pipeline Integration

# .github/workflows/k8s-integration.yml
name: Kubernetes Integration Tests

on: [push, pull_request]

jobs:
  integration-test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v4
        with:
          go-version: '1.22'

      - name: Install kind
        run: |
          curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.22.0/kind-linux-amd64
          chmod +x ./kind && sudo mv ./kind /usr/local/bin/kind

      - name: Install kubectl
        uses: azure/setup-kubectl@v3

      - name: Create kind cluster
        run: kind create cluster --name ci-test --config kind-config.yaml

      - name: Build and load test image
        run: |
          docker build -t myapp:${{ github.sha }} .
          kind load docker-image myapp:${{ github.sha }} --name ci-test

      - name: Deploy test dependencies
        run: |
          kubectl apply -f k8s/test/
          kubectl wait --for=condition=ready pod -l app=postgres --timeout=90s

      - name: Run integration tests
        env:
          TEST_IMAGE_TAG: ${{ github.sha }}
          KUBECONFIG: ~/.kube/config
        run: go test ./integration/... -v -timeout 10m

      - name: Collect logs on failure
        if: failure()
        run: |
          kubectl get events --all-namespaces
          kubectl get pods --all-namespaces -o wide
          kubectl logs -l app=myapp --tail=100 || true

      - name: Cleanup
        if: always()
        run: kind delete cluster --name ci-test

Common kind Testing Patterns

Pattern 1: Test namespace isolation Create a fresh namespace per test to avoid interference:

func createTestNamespace(t *testing.T, client *kubernetes.Clientset) string {
    t.Helper()
    ns := &corev1.Namespace{
        ObjectMeta: metav1.ObjectMeta{
            GenerateName: "test-",
        },
    }
    result, err := client.CoreV1().Namespaces().Create(context.Background(), ns, metav1.CreateOptions{})
    require.NoError(t, err)
    t.Cleanup(func() {
        client.CoreV1().Namespaces().Delete(context.Background(), result.Name, metav1.DeleteOptions{})
    })
    return result.Name
}

Pattern 2: Reuse cluster across test suite Creating a kind cluster per test is slow. Share one cluster, isolate via namespaces:

// TestMain sets up a shared cluster for the entire test package
func TestMain(m *testing.M) {
    setup()
    code := m.Run()
    teardown()
    os.Exit(code)
}

kind enables the full Kubernetes integration testing workflow in CI without any cloud costs. For most teams, this is the right default for verifying that Kubernetes manifests, Helm charts, and application code work together correctly.


HelpMeTest can run behavioral tests against applications deployed in Kubernetes, verifying end-to-end correctness after each deployment. Start free →

Read more

Start now free