Skip to Content
Skip to content
Shut Down a Go HTTP Server Gracefully With signal.NotifyContext
Intermediate
Tutorials

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.

Updated 4 min read GoDeployment and Containers

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

  1. Passing the canceled signal ctx to srv.Shutdown(ctx): Once SIGTERM fires, ctx is already canceled! Passing it to Shutdown causes Shutdown to return immediately with context.Canceled without draining active requests. Always derive shutCtx from a fresh context.Background() with a timeout (shorter than Kubernetes's 30s terminationGracePeriodSeconds).
  2. Treating http.ErrServerClosed as a fatal error: As soon as srv.Shutdown closes the listening socket, srv.ListenAndServe() always returns http.ErrServerClosed—that is the normal expected exit signal, not a crash!
  3. Closing db.Close() before srv.Shutdown finishes: In-flight requests still draining inside Shutdown may be running final SQL queries; call db.Close() only after srv.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): If SIGTERM arrives right as ListenAndServe errors, an unbuffered channel can block the server goroutine; use make(chan error, 1).
  • Calling srv.Close() instead of srv.Shutdown(shutCtx): Close() kills every active connection immediately without waiting for responses to finish.
  • Ignoring long-lived WebSocket or SSE streams: srv.Shutdown does not wait for hijacked WebSockets—register a shutdown hook or cancel a shared BaseContext to 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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.