How do I gracefully shut down in containers in Go projects?

Learn how to gracefully shut down Go applications running in containers. This guide covers best practices and essential code snippets for effective shutdown procedures, ensuring your applications terminate smoothly without losing any data.

Go, Graceful Shutdown, Container, Go Projects, Application Termination, Best Practices

package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    srv := &http.Server{Addr: ":8080", Handler: http.DefaultServeMux}

    // Channel to listen for interrupt signals
    stop := make(chan os.Signal, 1)
    signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)

    // Start the server in a goroutine
    go func() {
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            fmt.Println("ListenAndServe(): ", err)
        }
    }()

    // Wait for interrupt signal
    <-stop
    fmt.Println("Shutting down server...")

    // Create a timeout context for shutdown
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    // Shutdown the server with a timeout
    if err := srv.Shutdown(ctx); err != nil {
        fmt.Println("Server forced to shutdown: ", err)
    }
    fmt.Println("Server exiting")
}
        

Go Graceful Shutdown Container Go Projects Application Termination Best Practices