无法在主机和运行在Docker Alpine中的Golang服务器之间建立连接。

huangapple go评论70阅读模式
英文:

unable to connect between curl in host and golang server in docker alpine

问题

golang代码:

fmt.Println("服务器启动中...")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    name, _ := os.Hostname()
    resp := fmt.Sprintf("请求成功 %s", name)
    w.Write([]byte(resp))
})

http.ListenAndServe("127.0.0.1:8080", nil)

Dockerfile:

FROM alpine:latest
COPY ./server .
CMD ["./server"]

然后运行它:

$ docker run --rm -p 8080:8080 server
服务器启动中...

在容器中运行正常(需要安装curl):

$ docker exec 3c3 -it curl localhost:8080
请求成功 3c398d80ca79

但是在主机上无法正常工作

$ curl localhost:8080
curl: (52) Empty reply from server
$ nc localhost 8080 
$ # nc立即退出

如果我运行nc -l -p 8080而不是./server

$ docker run --rm -it -p 8080:8080 alpine:latest nc -l -p 8080

然后在主机上运行:

$ curl localhost:8080

然后我可以在容器中收到请求,一切正常。

那么在alpine镜像中使用curl访问golang服务器时出现了什么问题?

英文:

golang code:

fmt.Println("server starting...")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	name, _ := os.Hostname()
	resp := fmt.Sprintf("hit %s", name)
	w.Write([]byte(resp))
})

http.ListenAndServe("127.0.0.1:8080", nil)

Dockerfile:

FROM alpine:latest
COPY ./server .
CMD [ "./server" ]

Then run it:

$ docker run --rm -p 8080:8080 server
server starting...

It works in container(after curl installed):

$ docker exec 3c3 -it curl localhost:8080
hit 3c398d80ca79

But it doesn't work in host:

$ curl localhost:8080
curl: (52) Empty reply from server
$ nc localhost 8080 
$ # nc exit immediatly

If I run nc -l -p 8080 instead of ./server:

$ docker run --rm -it -p 8080:8080 alpine:latest nc -l -p 8080

and run it in host:

$ curl localhost:8080

Then I can get request in container, and everthing works well.

So what's the problem when curl the golang server in alpine image?

答案1

得分: 1

你的dockerfile中缺少EXPOSE 8080

英文:

You're missing EXPOSE 8080 in your dockerfile

答案2

得分: -1

我使用http.ListenAndServe(":8080", nil)代替,一切都正常工作!

英文:

I use http.ListenAndServe(":8080", nil) instead, everthing works well!

huangapple
  • 本文由 发表于 2021年6月15日 22:03:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/67987825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定