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