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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵