I have the following image
FROM golang:1.8.3
WORKDIR /go/src/x/x/program
RUN mkdir /logs
VOLUME ["/go/src/x/x/program", "/logs"]
CMD ["sh", "-c", "go install && program"]
My Go server listens to SIGINT in the following way
// ... Other stuff
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
signal.Stop(c)
// Server graceful shutdown
err := s.Shutdown(context.Background())
if err != nil {
fileLogger.Printf("could not shutdown server: %v", err)
} else {
fileLogger.Print("server successfully shutdown")
}
// ... Start server
But I'm failing to trap and handle SIGINT. I tried the following:
docker kill -s SIGINT <my_container>
docker-compose down/kill
docker exec -ti <my_container> /bin/bash
kill -SIGINT <go program PID>
Nothing gets logged, so I assume SIGINT wasn't handled by my program at all.
When testing, I managed to do it by doing the following (which isn't fit for production)
docker run -ti -v <local_path_to_log>:/logs <my_image> /bin/bash
go run *.go
CTRL + C
to interrupt processI see the logs in my file.
I also just figured out that the way my image is set up, it ends up having two processes running:
docker exec -ti <my_container> /bin/bash
root@xxx:/go/src/x/x/x# ps aux | grep program
root 1 0.0 0.0 4332 716 ? Ss 03:47 0:00 sh -c go install && program
root 32 0.0 0.3 335132 6624 ? Sl 03:47 0:00 program
root@xxx:/go/src/x/x/x# kill -SIGINT 32
So as shown above, killing the second process (and not PID 1) sends SIGINT to the program, which can than trap and handle it.
I know I'm close to a solution to sending SIGINT from outside of the container. But I can't grasp it yet.
What is the correct approach here to have a container that can receive a SIGINT to the correct process?
Docker passes signals to PID 1 process. In your case, since you are spawning a child process, you are not getting the signal. If there is only 1 processing in CMD, you can do something like:
CMD ["/bin/ping","localhost"]
If you are doing multiple operations like what you have put above, you can run a script in CMD and have signal processing in the script and pass it to your background process. The other option is to have only 1 command processing in CMD. You can do "go install" in previous step and just run executable in CMD.