Sobes.tech
Middle+

How to implement a graceful shutdown of a Go service in Kubernetes when deploying a new version?

sobes.tech AI

Answer from AI

To implement a graceful shutdown of a Go service in Kubernetes when deploying a new version, you need to properly handle the termination signal and give the service time to complete current operations.

Main steps:

  1. Handling the SIGTERM signal

In your Go application, you should listen for the system signal SIGTERM, which Kubernetes sends before stopping the container.

import (
    "os"
    "os/signal"
    "syscall"
    "context"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)

    go func() {
        <-sigs
        cancel() // signal to finish
    }()

    // Run main work with ctx
    run(ctx)
}
  1. Graceful shutdown considering the context

In the run function or handlers, check ctx.Done() and properly finish processing, such as closing connections, stopping goroutines.

  1. Kubernetes configuration
  • Ensure that terminationGracePeriodSeconds is set in the Deployment — the time Kubernetes will give the pod to terminate.
  • When SIGTERM is received, Kubernetes waits for the specified time before killing the container.
  1. Example
func run(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            // cleanup resources
            return
        default:
            // main logic
        }
    }
}

Thus, the service will shut down correctly without interrupting important operations, which is especially important during updates in Kubernetes.