本文介绍了Docker端口未公开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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\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

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

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标志运行
  • Running with the --expose 1337 flag

推荐答案

您的端口正确暴露,但是您的服务器正在侦听容器内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\n'+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\n'+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.

这篇关于Docker端口未公开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:32