server.listen(port, '127.0.0.1') 无法访问容器化节点服务器 [英] Containerized Node server inaccessible with server.listen(port, '127.0.0.1')

查看:45
本文介绍了server.listen(port, '127.0.0.1') 无法访问容器化节点服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I set up a simple Node server in Docker.

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
'+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

验证容器正在运行并且端口已映射:

Verify the container is running and ports are mapped:

$ 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

现在让我们附加到容器并验证服务器是否在里面运行:

Now let's attach to the container and verify the server is running inside:

$ docker exec -it 5909e87302ab7520884060437e19ef543ffafc568419c04630abffe6ff731f70 /bin/bash 

并在容器命令行中输入:

And in the container command line type:

root@5909e87302ab:/# curl http://localhost:1337
Hello World
Mon Feb 15 2016 16:28:38 GMT+0000 (UTC)

看起来不错吧?

问题

当我在主机上执行相同的 curl 命令(或使用浏览器导航到 http://localhost:1337)时,我什么也没看到.

When I execute the same curl command on the host (or navigate with my browser to http://localhost:1337) I see nothing.

知道为什么容器和主机之间的端口映射不起作用吗?

Any idea why the port mapping between container and host doesn't work?

我已经尝试过的事情:

  • 使用 --expose 1337 标志运行

推荐答案

您的端口已正确公开,但您的服务器正在侦听容器内 127.0.0.1 上的连接:

Your ports are being exposed correctly but your server is listening to connections on 127.0.0.1 inside your container:

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World
'+new Date);
}).listen(1337, '127.0.0.1');

你需要像这样运行你的服务器:

You need to run your server like this:

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World
'+new Date);
}).listen(1337, '0.0.0.0');

注意 0.0.0.0 而不是 127.0.0.1.

Note the 0.0.0.0 instead of 127.0.0.1.

这篇关于server.listen(port, '127.0.0.1') 无法访问容器化节点服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆