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 (

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {      
    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

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



  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码