Reputation: 7008
Created the docker file as following:
FROM node:boron
ADD package.json package.json
RUN npm install
ADD . .
EXPOSE 4500
CMD ["node","main.js"]
Building the app:
docker build -t "appname"
Running the app:
docker run -it "appname"
Inside main.js
, I have:
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);
});
when I run the app using docker command 'docker run -it "appname"`, I get the out to console:
Node app is running on port 3001
But when I browse, page is empty or nothing is loaded in the browser/output/view. It is supposed to pick up index.html
from response.render('public_html/');
Upvotes: 2
Views: 81
Reputation: 6477
You need to explicitly expose the port which your app is supposed to run on:
docker run -p 3001:3001 your-node-image
Then you can access your container's service on your docker host under http://localhost:3001, because -p 3001:3001
binds the host port 3001 (the first 3001 in the argument) to the container's port 3001 (the second 3001).
EXPOSE
from your Dockerfile only describes which ports are exposed by your application (which is in your Dockerfile 4500 and in your program port 3001...? Why are they different?). Publishing ports with -p
is also necessary to access the container, 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.
Additionally, the flags -it
appear to be useless with your service. You need these flags when you want to have an interactive session, e.g. when you're starting a shell in your container.
See here some more information about port exposal in the official documentation
Upvotes: 4