Search code examples
node.jsexpressdockerport

Docker node.js app not listening on port


I'm working on a node.js web application and use localhost:8080 to test it by sending requests from Postman. Whenever I run the application (npm start) without using Docker, the app works fine and listens on port 8080.

When I run the app using Docker, The app seems to be running correctly (it displays that it is running and listening on port 8080), however it is unreachable using Postman (I get the error: Could not get any response). Do you know what the reason for this could be?

Dockerfile:

FROM node:8  
WORKDIR /opt/service
COPY package.json .
COPY package-lock.json .
RUN npm i
COPY . .
EXPOSE 8080
CMD ["npm", "start"]

I build and run the application in Docker using:

docker build -t my-app . 
docker run my-app

I have tried binding the port as described below, but I also wasn't able to reach the server on port 8181.

docker run -p 8181:8080 my-app

In my application, the server listens in the following way (using Express):

app.listen(8080, () => {
    console.log('listening on port 8080');
})

I have also tried using:

app.listen(8080, '0.0.0.0', () => {
    console.log('listening on port 8080');
})

The docker port command returns:

8080/tcp -> 0.0.0.0:8181

Do you guys have nay idea what the reason for this could be?

UPDATE: Using the IP I obtained from the docker-machine (192.168.99.100:8181) I was able to reach the app. However, I want to be able to reach it from localhost:8181.


Solution

  • The way you have your port assignment setup requires you to use the docker machine's ip address, not your localhost. You can find your docker machines ip using:

    docker-machine ip dev
    

    If you want to map the container ip to your localhost ports you should specify the localhost ip before the port like this:

    docker run -p 127.0.0.1:8181:8080 my-app
    

    Similar question: