Shut Down a Go HTTP Server Gracefully With signal.NotifyContext
Handle SIGINT and SIGTERM with signal.NotifyContext, drain active requests with server.Shutdown(ctx), and test shutdown under -race. After this, deploys stop dropping in-flight HTTP requests.
Skip ahead
Already using signal.NotifyContext? Jump to Case 2: why passing the signal ctx to srv.Shutdown breaks draining or Case 3: Docker PID 1 SIGTERM traps.
When Kubernetes, Docker, or systemd deploys a new version of your Go server, it sends SIGTERM to the old container and waits a short grace period before killing it. If your server only calls log.Fatal(http.ListenAndServe(":8080", mux)), Go exits abruptly—cutting active checkouts, webhooks, and database transactions in half and causing 502 Bad Gateway errors on every deploy.
Go's standard library gives you zero-downtime graceful shutdown in ~30 lines using signal.NotifyContext and srv.Shutdown(shutCtx). Verified on Go 1.27.
Case 1: Complete graceful shutdown pattern
When srv.Shutdown(shutCtx) runs, Go immediately stops accepting new connections, closes idle keep-alive sockets, and waits for all in-flight HTTP handlers to finish writing their responses before returning:
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func run(ctx context.Context) error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
}
errCh := make(chan error, 1)
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
close(errCh)
}()
select {
case err := <-errCh:
return err
case <-ctx.Done():
slog.Info("shutting down gracefully")
shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(shutCtx)
}
}
func main() {
if err := run(context.Background()); err != nil {
fmt.Fprintln(os.Stderr, "server error:", err)
os.Exit(1)
}
}
Case 2: Three subtle bugs that break graceful shutdown
- Passing the canceled signal
ctxtosrv.Shutdown(ctx): OnceSIGTERMfires,ctxis already canceled! Passing it toShutdowncausesShutdownto return immediately withcontext.Canceledwithout draining active requests. Always deriveshutCtxfrom a freshcontext.Background()with a timeout (shorter than Kubernetes's 30sterminationGracePeriodSeconds). - Treating
http.ErrServerClosedas a fatal error: As soon assrv.Shutdowncloses the listening socket,srv.ListenAndServe()always returnshttp.ErrServerClosed—that is the normal expected exit signal, not a crash! - Closing
db.Close()beforesrv.Shutdownfinishes: In-flight requests still draining insideShutdownmay be running final SQL queries; calldb.Close()only aftersrv.Shutdown(shutCtx)returns.
Case 3: Why Docker shell-form CMD breaks SIGTERM
Writing CMD ./server in a Dockerfile starts /bin/sh -c ./server as PID 1—and /bin/sh frequently swallows SIGTERM without forwarding it to your Go binary, causing Docker to hang for 10 seconds and then send SIGKILL! Always use exec form:
ENTRYPOINT ["/app/server"]
Case 4: Testing shutdown deterministically in go test
Because run(ctx context.Context) error takes a parent context, your integration test can create ctx, cancel := context.WithCancel(context.Background()), start run(ctx) in a goroutine, hit /health, call cancel(), and verify run returns nil in milliseconds without sending real OS signals.
💡 Tip
Listening for both os.Interrupt (Ctrl+C during local dev) and syscall.SIGTERM (Docker/Kubernetes/systemd) ensures graceful shutdown works identically on your laptop and in production.
Common mistakes
- Using an unbuffered
errCh := make(chan error): IfSIGTERMarrives right asListenAndServeerrors, an unbuffered channel can block the server goroutine; usemake(chan error, 1). - Calling
srv.Close()instead ofsrv.Shutdown(shutCtx):Close()kills every active connection immediately without waiting for responses to finish. - Ignoring long-lived WebSocket or SSE streams:
srv.Shutdowndoes not wait for hijacked WebSockets—register a shutdown hook or cancel a sharedBaseContextto close streaming clients cleanly.
⚠ Warning
Make sure your shutCtx timeout (e.g., 10–20s) is comfortably shorter than your orchestrator's kill timeout (Docker default 10s, Kubernetes default 30s) so your cleanup code finishes before SIGKILL hits.
What happens if you skip this
Every routine deploy or pod scale-down drops active HTTP connections mid-flight—causing 502 errors, interrupted writes, and customer-visible blips during business hours.
Related course: Go Intermediate.
About
Handle SIGINT and SIGTERM with signal.NotifyContext, drain active requests with server.Shutdown(ctx), and test shutdown under -race. After this, deploys stop dropping in-flight HTTP requests.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.