我有 MacOS High Sierra,我的目标是在 MacOS 上运行 Node Web 应用程序而无需安装 Node (我想使用 docker 来做到这一点)。该 Web 应用程序通常是 Angular-Webpack(编译 + 运行开发服务器)。
Dockerfile:
FROM node
WORKDIR /work
CMD while true; do sleep 10000; done
EXPOSE 3002
线路CMD while ...
使得该容器在运行后不会被 docker 杀死 - 这允许我们“登录”到容器(通过 docker exec -it...
)。
运行容器的 Bash 脚本 run.cmd:
set -e
docker build -t node-cmd .
docker rm -f node-cmd |:
docker run -d --name node-cmd -p 3002:3002 -v /Volumes/work:/work node-cmd
docker exec -it node-cmd /bin/bash
哪里/Volumes/work
是我的 MacO 上包含 Angular 项目的目录。
这是文件 /work/tmp/example.js 中的示例应用程序(映射在容器中),该应用程序的问题是可见的(但是它们的主要目标是找到 webpack 开发服务器的正确配置) :
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n'+new Date);
}).listen(3002, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3002/');
所以首先我运行 run.cmd
- 这就是 docker ps
写:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e22188d8e136 node-cmd "/bin/sh -c 'echo \"R…" 16 seconds ago Up 15 seconds 0.0.0.0:3002->3002/tcp node-cmd
在容器内我输入命令:
root@5cd3773e7815:/work# cd tmp
root@5cd3773e7815:/work# node example.js &
[1] 18
root@5cd3773e7815:/work/tmp# Server running at http://127.0.0.1:3002/
所以服务器启动了。现在我测试:
root@5cd3773e7815:/work/tmp# curl 127.0.0.1:3002
Hello World
所以在docker内部一切正常。现在,当我转到我的 MacOS Chrome 浏览器 http://127.0.0.1:3002
时我明白了
This page isn’t working 127.0.0.1 didn’t send any data.
ERR_EMPTY_RESPONSE
如果我删除 -p 3002:3002
从 run.cmd 文件浏览器响应更改为
127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
我也尝试使用 docker run --ip=127.0.0.1...
但我收到消息
docker: Error response from daemon: user specified IP address is supported on user defined networks only.
当我尝试使用docker run --net=host ...
时它不会改变任何东西
我还想在运行时提及这一点 mysql
图片来源:docker run -p 3306:3306 ...
我工作正常(!) - 所以问题可能出在 node
图片(?)
问题:
- 如何“解锁”容器中的端口 3002 以允许主机浏览器连接容器内的服务?
- 如何使用
subdomain.local:3002
等子域也是吗? - 如何使用 webpack devServer(在 Angular 中使用)代替上面的子域
example.js
(我需要在具有单独子域的不同端口上运行许多角度网络应用程序)?
最佳答案
我认为此问题可能与您指定 127.0.0.1
作为主机有关。尝试使用 0.0.0.0
代替:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n'+new Date);
}).listen(3002, '0.0.0.0');
对于子域,您很可能需要编辑本地计算机上的 /etc/hosts
文件。
关于node.js - Docker 不公开 Node 和 webpack 开发服务器的端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51749513/