创建如下 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)。
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/