问题描述
过去两天,我在使用docker时遇到了麻烦,我可以解决。在docker doc之后,您可以使用 EXPOSE
公开容器侦听连接的端口。到目前为止,一切都很好!
this past two day I'm having trouble with docker and i can get it. Following to the docker doc you can expose the ports on which a container will listen for connections with EXPOSE
. So far, so good!
如果我的应用程序侦听端口8080,则应使用 EXPOSE 8080
公开我的docker容器并使用 docker run -p 80:8080
将其绑定到主主机的端口80。
If my app listen on port 8080 I should expose my docker container with EXPOSE 8080
and bind it to port 80 of the main host with docker run -p 80:8080
.
这是我的Dockerfile:
Here is my Dockerfile:
# DOCKER-VERSION 0.0.1
FROM ubuntu:14.10
# make sure apt is up to date
RUN apt-get update
# install nodejs and npm
RUN apt-get install -y nodejs-legacy npm git git-core
ADD package.json /root/
ADD server.js /root/
# start script
ADD start.sh /root/
RUN chmod +x /root/start.sh
EXPOSE 8080
CMD ./root/start.sh
而我的 start.sh
只是runan cd / root /
& npm install
& node server.js
。
And my start.sh
just runan cd /root/
& npm install
& node server.js
.
我有一个简单的express nodejs应用程序:
I got a simple express nodejs app:
var express = require('express');
// Constants
var PORT = 8080;
// App
var app = express();
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
这是我构建docker映像的方式: docker build -t app1。
以及我如何启动docker: docker run -it -p 80:8080 --name app1 app1
Here is how i build my docker image: docker build -t app1 .
And how i launch my docker: docker run -it -p 80:8080 --name app1 app1
真正连接的是什么,这是行不通的。为了使其正常工作,我必须将 EXPOSE 8080
更改为 EXPOSE 80
。我不明白。
What is really wired, this is not working. To make it work i have to change EXPOSE 8080
to EXPOSE 80
. I don't get it.
任何解释吗?
感谢阅读,
Tom
Thanks for reading,Tom
推荐答案
在您的nodejs应用程序中,您有一条指令 app.listen(PORT);
告诉nodejs启动服务器以侦听端口 PORT
上回送接口上的连接。
结果,您的应用程序将只能查看源自本地主机(容器本身)的连接。
In your nodejs app, you have the instruction app.listen(PORT);
which tells nodejs to start a server listening for connections on the loopback interface on port PORT
. As a result your app will only by able to see connections originating from localhost (the container itself).
您需要告诉您的应用以监听端口 PORT
上的所有接口:
You need to tell your app to listen on all interfaces on port PORT
:
app.listen(PORT, "0.0.0.0");
这样,它将看到来自Docker容器外部的连接。
This way it will see the connections originating from outside your Docker container.
这篇关于Docker EXPOSE。无法得到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!