Deploying a web application in a cloud environment involves multiple components working together seamlessly. One effective approach is deploying a Go Web API on Kubernetes, utilizing Traefik as an ingress controller. This setup provides scalability, load balancing, and simplified routing for your API services.

Prerequisites

  • A Kubernetes cluster (local or cloud-based)
  • kubectl configured to interact with your cluster
  • Helm package manager installed
  • Docker installed for containerizing your Go API
  • Traefik ingress controller installed in your cluster

Building the Go Web API

Start by creating a simple Go API. Here's an example of a basic web server:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, Kubernetes with Traefik!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Containerizing the API

Create a Dockerfile to containerize your Go application:

FROM golang:1.20-alpine

WORKDIR /app

COPY . .

RUN go build -o main .

EXPOSE 8080

CMD ["./main"]

Build and push your Docker image to a container registry:

docker build -t yourdockerhubusername/go-api:latest .
docker push yourdockerhubusername/go-api:latest

Deploying to Kubernetes

Create a deployment YAML file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-api-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: go-api
  template:
    metadata:
      labels:
        app: go-api
    spec:
      containers:
      - name: go-api
        image: yourdockerhubusername/go-api:latest
        ports:
        - containerPort: 8080

And a service YAML file:

apiVersion: v1
kind: Service
metadata:
  name: go-api-service
spec:
  type: ClusterIP
  selector:
    app: go-api
  ports:
  - port: 80
    targetPort: 8080

Configuring Traefik Ingress

Create an ingress resource to route external traffic to your API:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: go-api-ingress
  annotations:
    traefik.ingress.k8s.io/router.entrypoints: web
spec:
  rules:
  - host: api.yourdomain.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: go-api-service
            port:
              number: 80

Applying the Configuration

Apply all configurations to your Kubernetes cluster:

kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f ingress.yaml

Ensure that Traefik is running and correctly configured to handle ingress traffic. Once applied, your Go API will be accessible via http://api.yourdomain.com.

Conclusion

This example demonstrates how to deploy a simple Go Web API on Kubernetes, managed with Traefik ingress. This approach offers a scalable, flexible, and robust environment for deploying web services in the cloud.