我在Docker中设置了一个简单的Node服务器。
Dockerfile

FROM node:latest
RUN apt-get -y update
ADD example.js .
EXPOSE 1337
CMD node example.js
example.js
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n'+new Date);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
现在建立图像
$ docker build -t node_server .
现在在容器中运行
$ docker run -p 1337:1337 -d node_server
$ 5909e87302ab7520884060437e19ef543ffafc568419c04630abffe6ff731f70
验证容器正在运行并且端口已映射:
$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
5909e87302ab        node_server         "/bin/sh -c 'node exa"   7 seconds ago       Up 6 seconds        0.0.0.0:1337->1337/tcp   grave_goldberg
现在,让我们附加到容器并验证服务器是否在其中运行:
$ docker exec -it 5909e87302ab7520884060437e19ef543ffafc568419c04630abffe6ff731f70 /bin/bash
并在容器命令行中输入:
root@5909e87302ab:/# curl http://localhost:1337
Hello World
Mon Feb 15 2016 16:28:38 GMT+0000 (UTC)
看起来不错吧?
问题
当我在主机上执行相同的curl命令(或使用浏览器导航到http://localhost:1337)时,我什么都看不到。
知道为什么容器和主机之间的端口映射不起作用吗?
我已经尝试过的事情:
  • 使用--expose 1337标志
  • 运行

    最佳答案

    端口正确暴露,但服务器正在侦听容器内127.0.0.1上的连接:

    http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n'+new Date);
    }).listen(1337, '127.0.0.1');
    
    您需要像这样运行服务器:
    http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n'+new Date);
    }).listen(1337, '0.0.0.0');
    
    请注意0​​.0.0.0而不是127.0.0.1。

    关于networking - 容器化节点服务器无法通过server.listen(port, '127.0.0.1')访问,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35414479/

    10-11 21:58
    查看更多