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")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?