Azure  

Deploying Your Go Application on Azure Kubernetes Service (AKS)

Golang is known for its lightweight nature, concurrency, and performance, which is why many developers choose it to develop modern microservices and cloud-native applications. Azure Kubernetes Service (AKS) comes as a powerful and flexible platform when deploying these applications at scale.

This blog post will guide you through the end-to-end process of a simple Go application being containerized and setting it up for deployment to AKS. We are starting with writing the Go code and going all the way to setting up your AKS cluster and finally deploying your app.

Reasons To Use Go and AKS

  • Efficient Go: Go compiles to a single static binary, which makes it very lightweight and very fast to start up. Because scaling is quick and resource usage is efficient, this is useful for both containers and microservices.
  • AKS as Scalability and Management: AKS is a managed Kubernetes service, which essentially takes the operational burden of your Kubernetes control plane and gives you a powerful, self-healing, and scale-integrated service with all other Azure services.

Prerequisites

Before we start, make sure you have the following installed.

  • Go (version 1.16 or higher recommended)
  • Docker Desktop
  • Azure CLI
  • kubectl (Kubernetes command-line tool)

Step 1. Our Simple Go Application.

Let's create a basic "Hello World" Go application that will listen on a specific port.

Create a new directory (e.g., go-aks-app), and inside it, create a file named main.go.

// main.go
package main

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

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello from Go app on AKS! (Hostname: %s)\n", os.Getenv("HOSTNAME"))
}

func main() {
	http.HandleFunc("/", handler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080" // Default port
	}

	log.Printf("Starting server on port %s", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

This simple application.

  • Listens for HTTP requests on the port specified by the PORT environment variable (defaulting to 8080).
  • Responds with a greeting and the hostname of the pod it's running on.

Step 2. Containerizing Your Go Application with Docker.

Next, we'll create a Dockerfile to build a Docker image of our Go application. This file should be in the same directory as main.go.

# Dockerfile

# Use a minimal base image for Go applications
FROM golang:1.22-alpine AS builder

# Set working directory
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy the rest of the application source code
COPY . .

# Build the Go application
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o go-aks-app .

# Use a scratch image for the final, super-minimal image
FROM alpine/git:2.40.1 as git
FROM alpine/git:2.40.1 as ca-certs

FROM scratch
LABEL maintainer="Your Name <[email protected]>"

# Copy the built application from the builder stage
COPY --from=builder /app/go-aks-app /go-aks-app

# Copy SSL certificates for HTTPS (if your app makes external HTTPS calls)
COPY --from=ca-certs /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Expose the port your application listens on
EXPOSE 8080

# Command to run the application
CMD ["/go-aks-app"]

Now, build your Docker image locally.

docker build -t go-aks-app:v1 .

To test it locally docker run -p 8080:8080 go-aks-app:v1.

Then open http://localhost:8080 in your browser.

Step 3. Set up Azure Container Registry (ACR).

We need a place to store our Docker image so AKS can pull it. Azure Container Registry (ACR) is a private Docker registry service in Azure.

Create a Resource Group.

az group create --name go-aks-rg --location eastus

Create an Azure Container Registry.

az acr create --resource-group go-aks-rg --name mygoappacr --sku Basic

Log in to your ACR.

az acr login --name mygoappacr

Tag your Docker image for ACR.

docker tag go-aks-app:v1 mygoappacr.azurecr.io/go-aks-app:v1

Push your image to ACR.

docker push mygoappacr.azurecr.io/go-aks-app:v1

Step 4. Deploy Azure Kubernetes Service (AKS).

Now, let's create our AKS cluster.

Create an AKS cluster.

az aks create --resource-group go-aks-rg --name mygoappaks --node-count 2 --enable-managed-identity --attach-acr mygoappacr --generate-ssh-keys

Verify kubectl connectivity.

kubectl get nodes

Step 5. Deploy Your Go Application to AKS.

We'll use Kubernetes manifest files for deployment.

Deployment Manifest (deployment.yaml): This defines how your application's pods should run.

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-aks-app-deployment
  labels:
    app: go-aks-app
spec:
  replicas: 2 # Run 2 instances of your app
  selector:
    matchLabels:
      app: go-aks-app
  template:
    metadata:
      labels:
        app: go-aks-app
    spec:
      containers:
        - name: go-aks-app
          image: mygoappacr.azurecr.io/go-aks-app:v1 # <--- IMPORTANT: Replace with your ACR name!
          ports:
            - containerPort: 8080
          env:
            - name: PORT
              value: "8080"
      imagePullSecrets:
        - name: acr-secret # If you didn't use `--attach-acr` or need a direct secret

Service Manifest (service.yaml): This exposes your application to the internet.

# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: go-aks-app-service
spec:
  type: LoadBalancer # Expose the service externally via an Azure Load Balancer
  selector:
    app: go-aks-app
  ports:
    - protocol: TCP
      port: 80 # External port
      targetPort: 8080 # Container port

Deploy to AKS: Apply these manifest files using kubectl.

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

Step 6. Verify Deployment and Access Your Application.

Check Pods

kubectl get pods -l app=go-aks-app

Check Service

kubectl get service go-aks-app-service

Conclusion

The future is bright for you after achieving all that: designing a Go application, containerizing it with Docker, pushing it to Azure Container Registry, building an Azure Kubernetes Service cluster, and finally running your Go application on an AKS instance.

Certainly, this is just the first step in writing scalable, resilient, and cloud-native applications using Go and Azure. From here, you can explore some advanced Kubernetes features such as auto-scaling, ingress controllers, monitoring with Azure Monitor, and integrating with other Azure services such as databases or message queues.

Happy coding!