Skip to content

Instantly share code, notes, and snippets.

@manhdaovan
Last active July 3, 2023 05:43
Show Gist options
  • Save manhdaovan/b60ce1de6164cfea8e675064dbdc38e9 to your computer and use it in GitHub Desktop.
Save manhdaovan/b60ce1de6164cfea8e675064dbdc38e9 to your computer and use it in GitHub Desktop.
Testing graceful shutdown with PID != 1 in Docker container
FROM alpine:latest
WORKDIR /app
COPY . /app
ENTRYPOINT [ "ash", "entry.sh" ]
cd /app
./test_graceful
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
fmt.Println("main started")
shutdown := make(chan os.Signal, 2)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
select {
case s := <-shutdown:
fmt.Println("shutdown server by received signal:", s.String())
}
}
build-app:
GOOS=linux go build -o test_graceful main.go && \
chmod +x test_graceful
build-image: build-app
docker build -t test_graceful .
run-app-on-docker:
docker run -it test_graceful
@manhdaovan
Copy link
Author

manhdaovan commented Jul 3, 2023

  • Output when stop container (Ctr+C on terminal tab which running docker run ... command)
    ^Cshutdown server by received signal: interrupt
    
  • Output when stop container by docker stop containerID
    #nothing
    
  • Output of ps aux inside container (app run with PID = 7)
    /app # ps aux
    PID   USER     TIME  COMMAND
      1 root      0:00 ash entry.sh
      7 root      0:00 ./test_graceful
     15 root      0:00 ash
     21 root      0:00 ps aux
    
  • Conclusion:
    • PID1 has to forward the signal to child process(es) (app) in case app is not running with PID1
    • The app MUST implement logic to handle signal from OS to be able to graceful shutdown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment