Learn Gin Β· 12/12

Deployment and Production Readiness 🚒

8 min read

Deployment and Production Readiness 🚒

Welcome to the final frontier of our Gin journey! You've built a fantastic application, and it's running smoothly on your local machine. But now, it's time to release it into the wild world of production. This is where the real adventure begins. Getting your application ready for production is like preparing a spaceship for a long voyage; you need to ensure it's robust, reliable, and ready for anything the universe throws at it. Let's dive into the essential steps to make your Gin application production-ready.

1. Implementing Graceful Shutdown for Zero Downtime

The Problem: Imagine you're in the middle of an important online transaction, and suddenly, the server restarts for an update. Your transaction fails, and you're left frustrated. This happens when applications are forcefully stopped without allowing them to finish their current tasks. In a production environment, this can lead to data corruption, failed jobs, and a terrible user experience.

The Solution: Graceful Shutdown

A graceful shutdown is a process where the server, upon receiving a shutdown signal, stops accepting new requests but continues to process any ongoing requests until they are completed. Once all active requests are handled, the server shuts down cleanly. This ensures that no operations are abruptly terminated, leading to zero downtime for your users during deployments or maintenance.

How it Works in Gin:

Go's net/http package provides a Shutdown method that we can use to implement a graceful shutdown. We'll listen for system signals (like SIGINT or SIGTERM) and, upon receiving one, call this Shutdown method.

Here is a practical example of how to implement a graceful shutdown in your Gin application:

go
package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()
	router.GET("/", func(c *gin.Context) {
		time.Sleep(5 * time.Second)
		c.String(http.StatusOK, "Welcome Gin Server")
	})

	srv := &http.Server{
		Addr:    ":8080",
		Handler: router,
	}

	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal, 1)
	// kill (no param) default send syscanll.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	// catching ctx.Done(). timeout of 5 seconds.
	select {
	case <-ctx.Done():
		log.Println("timeout of 5 seconds.")
	}
	log.Println("Server exiting")
}

Under the Hood:
When you run this code and press Ctrl+C, the program will catch the SIGINT signal. Instead of immediately terminating, it will stop accepting new connections and wait for up to 5 seconds for existing requests to complete before shutting down.


2. Writing a Dockerfile for Your Gin Application

The Problem: You've developed your application on your machine, and it works perfectly. But when you deploy it to a server, it crashes because of missing dependencies or a different environment configuration. This is often referred to as the "it works on my machine" syndrome, a classic headache for developers.

The Solution: Docker 🐳

Docker allows you to package your application and all its dependencies into a standardized unit called a container. This container can run on any machine that has Docker installed, ensuring that your application's environment is consistent everywhere, from your local machine to production servers.

Creating a Dockerfile:

A Dockerfile is a text file that contains the instructions for building a Docker image. For Go applications, we can use a multi-stage build to create a small and secure production image.

A Production-Ready Dockerfile:

dockerfile
# Stage 1: Build the Go binary
FROM golang:1.19-alpine AS builder

# Set the Current Working Directory inside the container
WORKDIR /app

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

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source code
COPY . .

# Build the Go app
# -ldflags="-w -s" reduces the size of the binary by stripping debug information
# CGO_ENABLED=0 disables CGO for a statically linked binary
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-w -s" -o main .

# Stage 2: Create a minimal production image
FROM alpine:latest

# Set the Current Working Directory inside the container
WORKDIR /root/

# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/main .

# Expose port 8080 to the outside world
EXPOSE 8080

# Command to run the executable
CMD ["./main"]

Why a Multi-Stage Build?
The first stage (builder) uses a full Go development image to build our application binary. The second stage then copies only the compiled binary into a minimal alpine image. This results in a much smaller production image, which is more secure and faster to deploy. It's like baking a cake and then only shipping the cake, not the entire kitchen!


3. Structured Logging for Production (Integrating Zap/Logrus)

The Problem: Your application in production is misbehaving, and you need to figure out why. You look at the logs, but they are a chaotic mess of plain text strings, making it incredibly difficult to search for specific information or analyze patterns.

The Solution: Structured Logging

Structured logging is the practice of writing logs in a consistent, machine-readable format, typically JSON. Each log entry is a JSON object with key-value pairs, making it easy to parse, search, and analyze with log management tools.

Integrating a Logging Library:

While Go's built-in log package is fine for simple applications, for production, you'll want a more powerful library like Zap or Logrus. These libraries provide features like leveled logging (info, warn, error), structured logging with context, and high performance.

Example with Zap:

First, you'll need to install Zap:

bash
go get -u go.uber.org/zap

Here is how you can create a middleware in Gin to use Zap for logging requests:

go
package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func main() {
	// Initialize Zap logger
	logger, _ := zap.NewProduction()
	defer logger.Sync() // flushes buffer, if any

	router := gin.New()

	// Add a ginzap middleware, which:
	//   - Logs all requests, like a combined access and error log.
	//   - Logs to stdout.
	//   - RFC3339 with UTC time format.
	router.Use(func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery

		c.Next()

		end := time.Now()
		latency := end.Sub(start)
		if len(c.Errors) > 0 {
			// Log errors
			for _, e := range c.Errors.Errors() {
				logger.Error(e)
			}
		} else {
			logger.Info(path,
				zap.Int("status", c.Writer.Status()),
				zap.String("method", c.Request.Method),
				zap.String("path", path),
				zap.String("query", query),
				zap.String("ip", c.ClientIP()),
				zap.String("user-agent", c.Request.UserAgent()),
				zap.Duration("latency", latency),
			)
		}
	})

	router.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "Hello, World!")
	})

	router.Run(":8080")
}

Now, every request will produce a structured JSON log like this:

json
{"level":"info","ts":1678886400.123456,"caller":"main/main.go:42","msg":"/","status":200,"method":"GET","path":"/","query":"","ip":"::1","user-agent":"curl/7.77.0","latency":"1.234Β΅s"}

This is much easier to work with than a simple line of text!


4. Creating Health Check / Readiness Endpoints

The Problem: In modern, containerized environments managed by orchestrators like Kubernetes, the system needs to know if your application is running correctly. Is it alive? Is it ready to start receiving traffic? Without this information, the orchestrator might send traffic to a container that is still starting up or has crashed, leading to errors.

The Solution: Health Check Endpoints

These are special API endpoints that provide information about the application's status.

  • Liveness Probe (/healthz): This endpoint is used to check if the application is running. If this check fails, the orchestrator might decide to restart the container. It should be a simple check, like returning a 200 OK status.

  • Readiness Probe (/readyz): This endpoint indicates whether the application is ready to handle requests. For example, it might need to connect to a database or load some initial data before it can serve traffic. If this check fails, the orchestrator won't send traffic to this container until it becomes ready.

Implementing Health Checks in Gin:

go
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// A simple function to simulate a check against a dependency, like a database.
func checkDatabaseConnection() bool {
	// In a real application, you would have logic to check the DB connection.
	// For this example, we'll just return true.
	return true
}


func main() {
	router := gin.Default()

	// Liveness probe endpoint
	router.GET("/healthz", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})

	// Readiness probe endpoint
	router.GET("/readyz", func(c *gin.Context) {
		if checkDatabaseConnection() {
			c.JSON(http.StatusOK, gin.H{"status": "ready"})
		} else {
			c.JSON(http.StatusServiceUnavailable, gin.H{"status": "not ready"})
		}
	})

	router.Run(":8080")
}

By providing these endpoints, you are giving crucial information to the systems managing your application, which helps them make your service more reliable and resilient. Think of it as your application raising its hand and saying, "I'm here and alive!" or "Hold on, I'm almost ready to start working!".


Additional Resources and References

Challenge

You are tasked with enhancing a basic Gin web server to make it production-ready. Modify the provided Go code to implement structured logging, health check endpoints, and a graceful shutdown mechanism.

Requirements:

  1. Implement Health Check Endpoints:

    • Create a GET endpoint at /healthz. This liveness probe should respond with a 200 OK status and the JSON body: {"status": "up"}.
    • Create a GET endpoint at /readyz. This readiness probe should respond with a 200 OK status and the JSON body: {"status": "ready"}.
  2. Implement Structured Logging Middleware:

    • Create a Gin middleware function that logs every incoming request to standard output.
    • The log output must be a single line of structured JSON for each request.
    • The JSON log must contain the following keys: method (string), path (string), status (integer), and latency_ms (integer, representing the request processing time in milliseconds).
    • Note: Do not use an external logging library like Zap or Logrus. Use Go's standard encoding/json and log packages.
  3. Configure Graceful Shutdown:

    • Refactor the server startup logic to use a custom http.Server.
    • Start the server in a non-blocking manner (i.e., in a separate goroutine).
    • Listen for the syscall.SIGINT and syscall.SIGTERM signals.
    • Upon receiving one of these signals, initiate a graceful shutdown of the server with a timeout of 5 seconds. Use context.WithTimeout to enforce this deadline.
    • Print a log message to indicate that the server is shutting down and another when the shutdown is complete.

Expected result

Your final code should be a single, complete Go program (main.go) that successfully compiles and runs. When executed, it should start a Gin web server with the following characteristics:

  1. Endpoints:

    • GET /ping: The original endpoint, which should remain functional.
    • GET /healthz: Responds with 200 OK and {"status":"up"}.
    • GET /readyz: Responds with 200 OK and {"status":"ready"}.
  2. Logging:

    • For every request made to any endpoint, a JSON object is printed to standard output. For example, a request to /ping should produce a log similar to this:
    json
    {"latency_ms":2001,"method":"GET","path":"/ping","status":200}
  3. Shutdown Behavior:

    • The main function should not exit immediately after starting the server.
    • The program will set up a signal handler for SIGINT (Ctrl+C) and SIGTERM.
    • When one of these signals is received, the program will print a shutdown message, wait up to 5 seconds for existing requests (like a slow /ping request) to complete, and then exit cleanly, printing a final confirmation message.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.