无法从主机

时间:2016-09-25 12:46:46

标签: reactjs docker webpack-dev-server

我正在完成React.js的教程,我决定在Docker容器中工作。 Here是本教程的代码。

本教程使用在容器上的端口8080上运行的webpack-dev-server。我已在Dockerfile中公开了此端口,并使用-P运行我的容器以发布端口。在容器内,如果我wget http://localhost:8080,则会按预期下载index.html。但是,如果我从主机运行等效的PowerShell命令Invoke-WebRequest http://localhost:32769,我会在下面获得Invoke-WebRequest : The underlying connection was closed: The connection was closed unexpectedly.完整详细信息/重新执行步骤。

Dockerfile

FROM node
MAINTAINER Matthew Pirocchi <matthew.pirocchi@gmail.com>
RUN apt-get update && apt-get install -y vim
EXPOSE 8080

容器设置

docker run -itdP --name repro mpiroc/react-fundamentals
docker exec -it repro bash
# Following commands executed within container
mkdir -p /home/mpiroc/repos && cd /home/mpiroc/repos
git clone https://github.com/ReactjsProgram/React-Fundamentals.git
cd React-Fundamentals
git checkout video2
npm install
npm run start # start just runs `webpack-dev-server`

测试容器

# In a separate terminal
PS C:\Users\matth> docker exec -it repro bash
root@fd6c3102bc51:/# wget http://localhost:8080
... # index.html is downloaded as expected
root@fd6c3102bc51:/# exit
exit
PS C:\Users\matth> docker ps
CONTAINER ID        IMAGE                       COMMAND             CREATED             STATUS              PORTS                     NAMES
fd6c3102bc51        mpiroc/react-fundamentals   "node"              28 minutes ago      Up 28 minutes       0.0.0.0:32769->8080/tcp   repro
PS C:\Users\matth> Invoke-WebRequest http://localhost:32769
Invoke-WebRequest : The underlying connection was closed: The connection was closed unexpectedly.
At line:1 char:1
+ Invoke-WebRequest http://localhost:32769
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

为什么我无法从主机访问已发布的端口?

2 个答案:

答案 0 :(得分:3)

我在this question找到了答案。我需要更改npm run start命令:

"start": "webpack-dev-server"

"start": "webpack-dev-server --host 0.0.0.0"

这是因为在webpack-dev-server 1.8.0及更高版本中,默认情况下webpack-dev-server仅侦听localhost,而不是机器(本例中为容器)ip。<​​/ p>

答案 1 :(得分:0)

看起来你正在使用Docker for Windows运行。如果您使用docker-machine安装,请执行docker-machine ip default(您可能需要使用docker-machine ls并使用特定的节点名称而不是默认名称。然后连接到该IP地址以访问由Docker而不是localhost运行的Linux VM。所以,如果你得到:

docker-machine ip default
192.168.100.1

Invoke-WebRequest http://192.168.100.1:32769
....