无法连接到Windows上以docker-compose开头的容器的暴露端口 [英] Cannot connect to exposed port of container started with docker-compose on Windows
问题描述
我无法访问应通过docker-compose将端口公开给主机的应用程序.这是一个可重现的示例:
I'm having trouble accessing apps that should expose ports to the host via docker-compose. Here is a reproducible example:
我使用angular CLI创建一个新的angular应用程序:
I create a new angular app using the angular CLI:
ng new angular-docker
然后,我在该目录中创建一个包含以下内容的Dockerfile:
Then I create a Dockerfile with the following contents in that directory:
FROM node:8
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app
RUN npm install
EXPOSE 4200
CMD ["npm", "start"]
接下来,我在同一目录中创建一个docker-compose.yaml文件:
Next I create a docker-compose.yaml file in the same directory:
version: '3'
services:
angular:
build: .
container_name: angular-docker
volumes:
- ./src:/usr/src/app/src
ports:
- "4200:4200"
然后我跑:
docker-compose up
我等到在docker-compose输出中得到以下行
I wait until I get the following line in the docker-compose output
angular-docker | ** Angular Live Development Server is listening on localhost: 4200, open your browser on http://localhost:4200/ **
从 docker检查angular-docker
中,我看到端口转发规则到位:
From docker inspect angular-docker
I see that the port-forwarding rule is in place:
...
"Ports": {
"4200/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "4200"
}
]
},
...
现在,当我尝试在Chrome中访问 http://localhost:4200 时,我得到ERR_EMPTY_RESPONSE.
Now, when I try to go to http://localhost:4200 in Chrome, I get ERR_EMPTY_RESPONSE.
但是,当我使用 curl localhost:4200
时,当我使用 docker exec -it angular-docker bash
猛击到容器中时,会收到响应.
However, when I use docker exec -it angular-docker bash
to bash into the container, I get a response, when I curl localhost:4200
.
我的环境:
- 操作系统:Windows 10 Pro版本10.0.16299(内部版本16299)
- Docker:18.03.1-ce-win65(17513)
我认为这可能是防火墙问题.因此,为了调试,我没有运气就关闭了防火墙应用程序(我正在使用卡巴斯基安全软件).
I figured that this might be a firewall issue. So for debugging, I closed the firewall application (I'm using Kaspersky Internet Security), with no luck.
为什么我不能从裸露的端口访问容器?
Why can I not access the container from the exposed port?
netstat -an |findstr:4200"
返回以下内容:
Proto Local Address Foreign Address State
TCP 0.0.0.0:4200 0.0.0.0:0 LISTENING
TCP [::1]:4200 [::]:0 LISTENING
推荐答案
您不能在Docker容器内使用默认的 npm start
.
You can't use the default npm start
out of the box within a docker container.
一种替代方法是更新 package.json
中的命令,以像下面这样运行 ng serve -H 0.0.0.0
:
One alternative is to update that command in your package.json
to run ng serve -H 0.0.0.0
like this:
开始":"ng serve -H 0.0.0.0"
此额外的 -H 0.0.0.0
用于侦听容器中的所有接口.
This extra -H 0.0.0.0
is to listen to all the interfaces from the container.
然后,当您的端口映射正常工作时,您应该从主机将站点放在所需的端口 localhost:4200
上.
Then as your port mappings are working, you should get your site on the desired port localhost:4200
from the host machine.
这篇关于无法连接到Windows上以docker-compose开头的容器的暴露端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!