英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论