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

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

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

问题

golang代码:

  1. fmt.Println("服务器启动中...")
  2. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  3. name, _ := os.Hostname()
  4. resp := fmt.Sprintf("请求成功 %s", name)
  5. w.Write([]byte(resp))
  6. })
  7. http.ListenAndServe("127.0.0.1:8080", nil)

Dockerfile:

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

然后运行它:

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

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

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

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

  1. $ curl localhost:8080
  2. curl: (52) Empty reply from server
  3. $ nc localhost 8080
  4. $ # nc立即退出

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

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

然后在主机上运行:

  1. $ curl localhost:8080

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

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

英文:

golang code:

  1. fmt.Println("server starting...")
  2. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  3. name, _ := os.Hostname()
  4. resp := fmt.Sprintf("hit %s", name)
  5. w.Write([]byte(resp))
  6. })
  7. http.ListenAndServe("127.0.0.1:8080", nil)

Dockerfile:

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

Then run it:

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

It works in container(after curl installed):

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

But it doesn't work in host:

  1. $ curl localhost:8080
  2. curl: (52) Empty reply from server
  3. $ nc localhost 8080
  4. $ # nc exit immediatly

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

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

and run it in host:

  1. $ 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:

确定