this past two day I'm having trouble with docker and i can get it. Following to the docker doc you can expose the ports on which a container will listen for connections with EXPOSE
. So far, so good!
If my app listen on port 8080 I should expose my docker container with EXPOSE 8080
and bind it to port 80 of the main host with docker run -p 80:8080
.
Here is my Dockerfile:
# DOCKER-VERSION 0.0.1
FROM ubuntu:14.10
# make sure apt is up to date
RUN apt-get update
# install nodejs and npm
RUN apt-get install -y nodejs-legacy npm git git-core
ADD package.json /root/
ADD server.js /root/
# start script
ADD start.sh /root/
RUN chmod +x /root/start.sh
EXPOSE 8080
CMD ./root/start.sh
And my start.sh
just runan cd /root/
& npm install
& node server.js
.
I got a simple express nodejs app:
var express = require('express');
// Constants
var PORT = 8080;
// App
var app = express();
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
Here is how i build my docker image: docker build -t app1 .
And how i launch my docker: docker run -it -p 80:8080 --name app1 app1
What is really wired, this is not working. To make it work i have to change EXPOSE 8080
to EXPOSE 80
. I don't get it.
Any explanation?
Thanks for reading, Tom
In your nodejs app, you have the instruction
app.listen(PORT);
which tells nodejs to start a server listening for connections on the loopback interface on portPORT
. As a result your app will only by able to see connections originating from localhost (the container itself).You need to tell your app to listen on all interfaces on port
PORT
:This way it will see the connections originating from outside your Docker container.