Deploying a Go application using Kubernetes involves several steps from containerizing the application to creating Kubernetes manifests and finally deploying them onto a Kubernetes cluster. In this article, we'll go through a step-by-step guide to help you deploy your Go app using Kubernetes.
Step 1: Containerize Your Go Application
First, you need to containerize your Go application using Docker. Ensure you have Docker installed and running on your machine.
// main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Kubernetes!")
}
Create a Dockerfile for your Go application:
# Dockerfile
FROM golang:1.17 as builder
WORKDIR /app
COPY . .
RUN go mod tidy
RUN go build -o main .
FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/main .
CMD ["./main"]
Build and tag your Docker image:
docker build -t my-go-app:1.0 .Step 2: Push the Docker Image to a Registry
You'll need a Docker registry where your image will be stored. You can use Docker Hub or any other container registry.
docker tag my-go-app:1.0 /my-go-app:1.0
docker push /my-go-app:1.0Step 3: Create Kubernetes Deployment and Service
Next, create a Kubernetes manifest file to define a deployment and a service for your Go application:
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: go-app-deployment
spec:
replicas: 3
selector:
matchLabels:
app: go-app
template:
metadata:
labels:
app: go-app
spec:
containers:
- name: go-app
image: /my-go-app:1.0
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: go-app-service
spec:
selector:
app: go-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer
Step 4: Deploy to Kubernetes
With your YAML files ready, apply them to your Kubernetes cluster:
kubectl apply -f deployment.yamlStep 5: Verify Deployment
Check if your pods are running and the service is exposed.
kubectl get pods
kubectl get servicesThe above command will show the running status of pods and services. Access your application using the external IP of your service:
Your Go application is now successfully deployed on Kubernetes. You can scale it, update it, or manage it using Kubernetes resources as needed.