javascript - 无法对 NodeApp 进行 dockerize

标签 javascript node.js docker

创建如下 docker 文件:

FROM node:boron

ADD package.json package.json

RUN npm install
ADD . .

EXPOSE 4500

CMD ["node","main.js"]

构建应用程序:

docker build -t“应用程序名称”

运行应用程序:

docker run -it“应用程序名称”

main.js 中,我有:

var express = require("express");
var app = express();
var path = require('path');
var http = require('http');
var https = require('https');
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
var request = require("request");

var port = process.env.PORT || 3001;
app.set('port', (port));
app.listen(app.get('port'), function () {
    console.log('Node app is running on port', app.get('port'));
});

//app.use('/', express.static(path.join(__dirname, '/public_html')))
app.use('/', express.static(__dirname + '/public_html'));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({
    limit: '5mb',
    extended: false
}));


app.get('/', function(request, response) {
  response.render('public_html/');
});

//app.get('/', function (req, res, next) {
//    res.sendFile('/index.html');
//});

app.use('*', function (req, res, err) {
//    console.log('error:  ', err);
});

当我使用 docker 命令 'docker run -it "appname"` 运行应用程序时,我得到控制台:

Node 应用程序正在端口 3001 上运行

但是当我浏览时,页面是空的或者浏览器/输出/ View 中没有加载任何内容。它应该从 response.render('public_html/');

中获取 index.html

最佳答案

您需要显式公开您的应用程序应该运行的端口:

docker run -p 3001:3001 your-node-image

然后您可以在 http://localhost:3001 下访问 docker 主机上的容器服务。 ,因为 -p 3001:3001 将主机端口 3001(参数中的第一个 3001)绑定(bind)到容器的端口 3001(第二个 3001)。

Dockerfile 中的

EXPOSE 仅描述了应用程序公开的端口(在 Dockerfile 4500 和程序端口 3001 中...?为什么它们不同?)。要访问容器,还需要使用 -p 发布端口,see the docs :

The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. EXPOSE does not make the ports of the container accessible to the host. To do that, you must use either the -p flag to publish a range of ports or the -P flag to publish all of the exposed ports.

此外,标志 -it 似乎对您的服务没有用处。当您想要进行交互式 session 时,例如,您需要这些标志。当您在容器中启动 shell 时。

在此处查看有关端口公开的更多信息 in the official documentation

关于javascript - 无法对 NodeApp 进行 dockerize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43892075/

相关文章:

node.js - Jest/Ts-Jest/Babel : Debug Failure. 错误表达式:输出生成失败

javascript - 为什么在 Javascript/Typescript 上有这么多种导入/导出

macos - 如何连接到 Mac 上 Docker (1.12.0) 容器中的 Postgres 服务器?

macos - 无法从主机访问 Docker swarm 中的 Web 服务器

javascript - 将 JSON 放入 JSON 中

javascript - 文本输入内的按钮 - HTML

node.js - Hubot - 从文件加载环境变量

docker - 使用 docker 模板化配置文件

javascript - 如何在casperjs中加载另一个页面?

javascript - ajax 调用 JavaScript 中的正确 URL