gpt4 book ai didi

javascript - 无法对 Node 应用程序进行 docker 化

转载 作者:搜寻专家 更新时间:2023-11-01 00:29:16 25 4
gpt4 key购买 nike

创建如下 docker 文件:

FROM node:boron

ADD package.json package.json

RUN npm install
ADD . .

EXPOSE 4500

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

构建应用:

docker build -t "appname"

运行应用:

docker run -it "appname"

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 - 无法对 Node 应用程序进行 docker 化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43892075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com