简体   繁体   English

Docker:无法打开从容器到主机的端口

[英]Docker: cannot open port from container to host

I'm using Docker for Mac .我正在使用Docker for Mac I have a container that run a server, for example my server is run on port 5000. I have exposed this port on Dockerfile我有一个运行服务器的容器,例如我的服务器在端口 5000 上运行。我在Dockerfile上公开了这个端口

When my container is running, I connect to this container and check and if this server is working or not by running below command and see that it returns data (a bunch of html and javascript)当我的容器运行时,我连接到该容器并通过运行以下命令检查该服务器是否正常工作,并查看它是否返回数据(一堆 html 和 javascript)

wget -d localhost:5000

Notes, I start this container and also publish port outside by command:注意,我启动这个容器并通过命令在外部发布端口:

docker run -d -p 5000:5000 <docker_image_name>

But at docker host (is my mac and running El Capitan), I open chrome and go to address localhost:5000 .但是在 docker 主机(是我的 mac 并运行 El Capitan),我打开 chrome 并转到地址localhost:5000 It doesn't work.它不起作用。 Just a little note, if I go to any arbitrary port such as localhost:4000 I see error message from chrome such as:请注意,如果我转到任何任意端口,例如localhost:4000 ,我会看到来自 chrome 的错误消息,例如:

This site can’t be reached
localhost refused to connect.

But error message for localhost:5000 is:但是localhost:5000的错误消息是:

The localhost page isn’t working
localhost didn’t send any data.

So it seems I have configured work "a little" but something wrong.所以看来我已经“稍微”配置了工作,但出了点问题。 Please tell me how to fix this.请告诉我如何解决这个问题。

Please check the program in container is listening on interface 0.0.0.0.请检查容器中的程序是否正在侦听接口 0.0.0.0。

In container, run command:在容器中,运行命令:

ss -lntp

If it appears like:如果它看起来像:

LISTEN  0   128   127.0.0.1:5000  *:*

that means your web app only listen at localhost so container host cannot access to your web app.这意味着您的 Web 应用程序仅在 localhost 上侦听,因此容器主机无法访问您的 Web 应用程序。 You should make your server listen at 0.0.0.0 interface by changing your web app build setting.您应该通过更改您的 Web 应用程序构建设置让您的服务器在0.0.0.0接口上侦听。

For example if your server is nodejs app:例如,如果您的服务器是 nodejs 应用程序:

var app = connect().use(connect.static('public')).listen(5000, "0.0.0.0");

If your server is web pack:如果你的服务器是 webpack:

 "scripts": {
    "dev": "webpack-dev-server --host 0.0.0.0 --port 5000 --progress"
  }

I had this problem using Docker for Mac, trying to run an Angular2 app.我在使用 Docker for Mac 时遇到了这个问题,试图运行 Angular2 应用程序。

I fixed the issue by changing the start script in package.json to我通过将package.json中的start脚本更改为

"scripts": {
    "start": "ng serve --host 0.0.0.0"
}

Previously start was only ng serve .以前start只是ng serve

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM