doulai8128 2017-07-31 04:03
浏览 53
已采纳

无法将SIGINT捕获在Docker容器中

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>
  • (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.

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)