我试图“Dockerize”一个相当大的,复杂的Node.js应用程序,其大致结构如下:
星云[项目的根目录;运行Node.js应用程序]
| __CosmosD3 [包含所有HTML和JS文件的目录]
| __Nebula-Pipeline [包含大多数执行所有繁重计算的Python文件的目录]
我们这个项目的标准安装过程相当复杂,因为所有互连的部分都必须完美地协同工作,以使我们的前端JS文件能够与我们的后端Python脚本进行通信。对于Linux / Unix系统,这是一个粗略的过程(命令在Nebula目录中运行):
pip install --upgrade pip
以确保使用最新的pipsudo apt-get install libzmq-dev npm nodejs-legacy
安装Node.js,npm和zmqnpm install
来安装我们的Node.js包依赖项pip install -e ./Nebula-Pipeline
以安装所有Python依赖项npm start
运行应用程序。默认端口是8081
,因此应该可以通过localhost:8081
访问应用程序。与此项目非常相似的项目已经“Dockerized”。通过调整其他项目的Dockerfile以更接近地对应上面的步骤,这是我创建的Dockerfile:
FROM ubuntu:16.04
RUN mkdir /www
WORKDIR /www
RUN apt-get update
RUN apt-get install -y libzmq-dev npm nodejs-legacy python python-pip
RUN apt-get update && \
apt-get install -y openjdk-8-jdk && \
apt-get install -y ant && \
apt-get clean;
# Fix certificate issues, found as of
# https://bugs.launchpad.net/ubuntu/+source/ca-certificates-java/+bug/983302
RUN apt-get update && \
apt-get install ca-certificates-java && \
apt-get clean && \
update-ca-certificates -f;
# Setup JAVA_HOME, this is useful for docker commandline
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JAVA_HOME
##COPY ./lib/ /opt/lib
RUN pip install --upgrade pip
COPY ./Nebula /www
RUN ls -a /www
RUN npm install
RUN pip install -e /www/Nebula-Pipeline
EXPOSE 8081
CMD ["npm", "start"]
当我使用docker build -t nebulaserver
运行此Dockerfile时,似乎成功创建了图像。当我使用docker run -p 8081:8081 nebulaserver
运行图像时,我得到以下打印输出,似乎表明一切都在正常工作。 (请注意,“PORT:8081”打印输出是对Node.js应用程序正在使用的端口的确认。)
Michelles-MacBook-Pro-8$ docker run -p 8081:8081 nebulaserver
> [email protected] start /www
> node app.js
PORT:
8081
但是,当我随后尝试连接到localhost:8081
时,我没有得到任何回应。另外,当我收到对其中一个HTML页面的请求时,我希望看到我的Node.js服务器有额外的打印输出。我也没有看到这些打印输出。就像端口转发不能正常工作一样。根据我读过的所有内容,我应该正确地做事,但我以前从未使用过Docker,所以也许我错过了什么?
任何人都知道我可能做错了什么?
编辑:这是我的app.js文件,如果有助于弄清楚发生了什么...
/*Import packages required in package.json */
/*Add these packages from the ../node_modules path*/
var express = require('express');//A lightweight nodejs web framework
var path = require('path');//Ability to join filepaths to filenames.
var favicon = require('serve-favicon');//Set prefered icon in browser URL bar. Unused?
var logger = require('morgan');//HTTP request logger. Unused?
var cookieParser = require('cookie-parser');//Stores cookies in req.cookies
var bodyParser = require('body-parser');//Middleware parser for incoming request bodies,
/* REST API routes */
var routes = require('./routes/index');//Points to /routes/index.js. Currently, index.js points to CosmosD3/CosmosD3.html
/* Connect to the databases */
//var mongo = require('mongodb');
//var monk = require('monk');
//var db = monk('localhost:27017/nodetest');
//var datasets = monk('localhost:27017/datasets');
/* The HTTP request handler */
var app = express();//Creates app from express class. (Baseline famework for an app. No web functionality).
var debug = require('debug')('Nebula:server');//Require the debug module. Pass it scoping 'Nebula:server'
var http = require('http').Server(app);//Create an http server on top of app.
/* The Socket.io WebSocket module */
var io = require('socket.io')(http);//Create an io/websocket on top of http object.
/* Our custom Nebula module handles the WebSocket synchronization */
var nebula = require('./nebula')(io);//Creates nebula layer on top of io.
/* Set the port we want to run on */
var port = process.env.PORT || 8080;
//app.set('port', port);
var host = '0.0.0.0';
app.listen(port, host);
console.log(`Running on http://${host}:${port}`);
/* view engine setup, currently not used */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
/* Expose everything in public/ through our web server */
app.use(express.static(path.join(__dirname, 'public')));
app.use("/cosmos", express.static(path.join(__dirname, 'CosmosD3')));
// Make our db accessible to our router
//app.use(function(req, res, next){
// req.db = db;
// req.datasets = datasets;
// next();
//});
/* Initiate the REST API */
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = (typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port);
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = http.address();
var bind = (typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port);
debug('Listening on ' + bind);
}
/**
* Listen on provided port, on all network interfaces.
*/
http.listen(port);
http.on('error', onError);
http.on('listening', onListening);
我终于想通了!!经过大量的挖掘,我发现Docker应用程序的默认IP是http://192.168.99.100而不是http://localhost。我从这里得到了答案:
https://forums.docker.com/t/docker-running-host-but-not-accessible/44082/13
我之前遇到过这个问题(正如his comment中@davidmaze所提到的那样)我不得不改变我的应用正在收听的主机。在我的情况下,我使用的是Express framework,(尽管文档暗示其他情况)只听localhost(127.0.0.1
),我需要它来听0.0.0.0
。请参阅第58行-66(构成Create the Node.js app示例的Dockerizing a Node.js web app部分中的第二个代码块),以便他们明确告诉express来听0.0.0.0
。
我认为你的问题是由于恶魔必须将其关闭,否则进程将在启动后立即停止。所以在你的cmd中你应该添加类似“-g”,“守护进程关闭”的东西。
或者使用主管来保持你的pid运行