doulai5585 2019-01-19 13:55
浏览 131
已采纳

Docker在运行Go Server时没有响应

I cannot stop docker golang web server in docker container by sending Interrupt Signal. I have following main.go:

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {      
        w.Write([]byte("hello"))
    })
    log.Fatal(http.ListenAndServe(":1818", nil))
}

And Dockerfile:

FROM golang:1.11.4-alpine3.8
WORKDIR /go/src/server
COPY main.go main.go
CMD ["go", "run", "main.go"]

I build:

docker build -t goserver .

and run image:

docker run -p 1818:1818 goserver

At this moment server is running. When I hit Ctrl+C in my console container (and server process) is still running and the only way to stop is by calling docker to do it. I would like to know how to handle such behaviour so that server and container stops when hitting Ctrl+C.

Docker version 18.09.1

  • 写回答

2条回答 默认 最新

  • dongzhangnong2063 2019-01-19 15:01
    关注

    You're using go run, so you're sending the signal to the go tool, not your server process. You can interrupt the sever started by go run in a shell, because ctrl+c in a shell sends the signal to the entire process group.

    There's also no reason to compile the executable every time you start the container (which can incur much more overhead as your program expands). Building the executable when creating the image is more efficient, and lets you execute the server directly.

    An example docker file:

    FROM golang:1.11.4-alpine3.8
    WORKDIR /go/src/server
    COPY main.go main.go
    RUN go build
    CMD ["./server"]
    

    See a similar question here, where the process is a shell rather than the go tool:

    Sending signals to Golang application in Docker

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体