Accelerating Your Kubernetes Workflow with Kind & Tilt

Accelerating Your Kubernetes Workflow with Kind & Tilt

Kubernetes development can be time-consuming if you’re waiting on lengthy build cycles or re-deployments for every code change. By combining Kind (Kubernetes IN Docker) with Tilt, you can spin up a local Kubernetes cluster and quickly iterate on your code changes with live syncing and automated rebuilds.

Prerequisites

Before you begin, ensure you have the following installed:

  • Docker: Kind runs Kubernetes nodes as Docker containers.
  • kubectl: For interacting with your Kubernetes cluster.
  • Kind: To run a local Kubernetes cluster.
  • Tilt: To manage build & deployment automation.

Also, basic familiarity with Kubernetes manifests and containerized applications is beneficial.

Installing Kind and Tilt

Installing Kind

Using Go (recommended):

go install sigs.k8s.io/[email protected]        

Alternatively, you can download a binary from the Kind releases page.

Verify the installation:

kind version        

Installing Tilt

Using Homebrew (macOS/Linux):

brew install tilt-dev/tap/tilt        

Using the installation script:

curl -fsSL https://raw.githubusercontent.com/tilt-dev/tilt/master/scripts/install.sh | bash        

Verify Tilt installation:

tilt version        

Setting Up a Kind Cluster

Create a New Kind Cluster

Kind creates a local Kubernetes cluster that runs as Docker containers. Execute:

kind create cluster --name dev-cluster        

This command:

  • Creates a new cluster named dev-cluster.
  • Automatically configures your kubectl context to use the new cluster.

Verify the Cluster

Check that your cluster is up and running:

kubectl cluster-info --context kind-dev-cluster        

Integrating Tilt with Kind

Tilt uses your current Kubernetes context to deploy resources. Since Kind updates your kubectl context automatically, Tilt will pick up the Kind cluster by default. You can also explicitly set the Kubernetes context in your Tiltfile if necessary.

Creating a Sample Project

Let’s assume you have a simple web service project with the following structure:

my-app/
├── Dockerfile
├── main.go
├── k8s/
│   └── deployment.yaml
└── Tiltfile        

Sample Dockerfile

# Use a base image with Go installed
FROM golang:1.23-alpine

WORKDIR /app

# Copy go.mod to leverage Docker cache
COPY go.mod ./
RUN go mod download

# Copy the source code
COPY . .

# Build the application
RUN go build -o my-app .

# Expose port 8080
EXPOSE 8080

# Run the application
CMD ["./my-app"]        

Sample main.go

package main

import (
	"fmt"
	"log"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, Kind & Tilt!")
}

func main() {
	http.HandleFunc("/", handler)
	log.Println("Starting server on port 8080...")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatalf("Server failed to start: %v", err)
	}
}        

Sample Kubernetes Deployment (k8s/deployment.yaml)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-app:dev
        ports:
        - containerPort: 8080        

To create the go.mod file:

go mod init golangapp        

Writing a Tiltfile

The Tiltfile is the configuration script that instructs Tilt how to build your image, sync code changes, and deploy to Kubernetes.

Sample Tiltfile

# Specify the Kubernetes context (optional)
k8s_context('kind-dev-cluster')

# Build the Docker image. The first argument is the image name.
docker_build('my-app:dev', '.', live_update=[
    # Sync local changes in the current directory to /app in the container.
    sync('.', '/app'),
    # Optionally, run a command if specific files change (e.g., dependency updates).
    run('go mod download', trigger=['go.mod', 'go.sum'])
])

# Load Kubernetes manifests from the k8s directory.
k8s_yaml('k8s/deployment.yaml')

# Set up a resource with port forwarding (if needed).
k8s_resource('my-app', port_forwards=8080)        

The k8s_context ensures Tilt uses the Kind cluster, while docker_build builds the Docker image and sets up a live update mechanism to sync file changes, such as code updates, directly into the container. The sync directive handles real-time copying of changes from the local directory to the container, and run executes specified commands when certain files change, such as updating dependencies. The k8s_yaml function deploys the necessary Kubernetes manifests, and k8s_resource configures port forwarding, enabling access to your service locally.

Running Tilt

Start Tilt

From your project directory (where your Tiltfile is located), run:

tilt up        

This command opens a web UI (usually at https://localhost:10350) that shows real-time logs, build status, and resource details.

Workflow with Tilt

Tilt streamlines the development workflow by automatically building and deploying changes whenever files are modified, ensuring a seamless integration process. Its live sync feature instantly reflects code changes in the running container, significantly reducing the time between coding and testing. Additionally, the Tilt UI provides comprehensive logs and monitoring capabilities, allowing developers to inspect logs, track resource health, and efficiently troubleshoot issues.

Advanced Usage and Tips

Customizing Live Updates

You can fine-tune the live update rules by excluding specific files or directories to prevent unnecessary updates and by adding additional run steps to handle tasks such as reloading configuration or assets, ensuring a more efficient and controlled development workflow.

Debugging with Tilt

Tilt’s UI offers a unified view to monitor build progress, track the status of Kubernetes resources, and inspect logs from running containers, providing developers with real-time insights for efficient debugging and workflow management.

Iterative Development

Tilt provides rapid feedback by triggering incremental rebuilds and live updates with each file change, significantly reducing the full build-deploy cycle. Its UI also ensures efficient error handling by immediately displaying errors, allowing developers to address issues before they accumulate.

Cleaning Up

When finished with your session:

Close Tilt by pressing Ctrl+C in your terminal.? Delete the Kind cluster (if desired):

kind delete cluster --name dev-cluster        

Combining Kind and Tilt allows developers to build an efficient local Kubernetes environment that reflects code changes almost immediately. This integrated approach enhances your ability to experiment with configurations, prototype rapidly, and iterate continuously, ultimately reducing the gap between coding and deployment. By leveraging Tilt’s live update features alongside Kind’s lightweight cluster setup, you create a development workflow that not only accelerates your feedback loop but also makes the debugging and refinement process much more seamless.

?

要查看或添加评论,请登录

Christopher Adamson的更多文章