doulai8128 2017-07-31 04:03
浏览 53


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() {

    // 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>
  • (with compose) docker-compose down/kill
  • docker exec -ti <my_container> /bin/bash
    • (followed by) 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 process

I 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?

  • 写回答

1条回答 默认 最新

  • dongpu42006096 2017-07-31 04:31

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?