Golang Web服务器无法从Docker访问。

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

Golang Webserver can't be accessed from Docker

问题

我正在使用Go语言中的Gorilla框架来暴露一个Web服务。我在/hello路径下有一个“Hello World”端点,在Postman、浏览器或curl中访问时都能正常工作。

问题出现在我将其与Docker捆绑时。我的Dockerfile如下所示:

FROM alpine
COPY ./target/himer-users-go /app
ENV PORT 9000
RUN echo $PORT
ENTRYPOINT /app
EXPOSE ${PORT}

现在我可以通过ssh进入容器,并使用wget来ping服务器(因为alpine不包含curl)。

但是当我像这样运行镜像时:

docker run -d -p 9000:9000 namespace/image

我无法从主机系统以任何方式访问服务器。

非常感谢您的帮助。

英文:

I am using the Gorilla framework in Go to expose a webservice. I have a "Hello World" endpoint at /hello which works fine when hit from Postman, browser or curl.

The problem arises when I bundle it with Docker. My Dockerfile is as below

FROM alpine
COPY ./target/himer-users-go /app
ENV PORT 9000
RUN echo $PORT
ENTRYPOINT /app
EXPOSE ${PORT}

Now I can ssh into the container and ping the server using wget (since alpine doesn't come bundled with curl)

But when I run the image like

docker run -d -p 9000:9000 namespace/image

I can't access the server in any way from my host system.

Any help would be greatly appreciated.

答案1

得分: 3

我通过将服务器暴露在0.0.0.0而不是localhost上来解决了这个问题。

问题是我告诉我的Web服务器只接受发送到localhost的请求。由于Docker进行的网络操作,所有发送到Web服务器的流量都不会被识别为发送到localhost。通过告诉Web服务器监听0.0.0.0,我实际上是在告诉它不关心流量最初发送到哪里,它将接受所有流量。

英文:

I solved it by exposing the server at 0.0.0.0 instead of localhost

The problem is that I've told my webserver to only serve requests sent to localhost. Because of the network mangling that Docker does, none of the traffic showing up to your webserver look to the webserver as though they were sent to localhost. By telling the webserver to listen on 0.0.0.0, I'm effectively telling it that it doesn't care where the traffic was originally sent and it will accept it all.

huangapple
  • 本文由 发表于 2017年7月9日 19:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/44996153.html
匿名

发表评论

匿名网友

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

确定