I have a simple Node.js/Express app:
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
It works fine when I start it like: node src/app.js
Now I'm trying to run it in a Docker container. Dockerfile is:
FROM node:8
WORKDIR /app
ADD src/. /app/src
ADD package.json package-lock.json /app/
RUN npm install
COPY . /app
EXPOSE 3000
CMD [ "node", "src/app.js" ]
It starts fine: docker run <my image>:
Listening on port 3000
But now I cannot access it in my browser: http://localhost:3000
This site can’t be reached localhost refused to connect.
Same happen if I try to run it within docker-compose:
version: '3.4'
services:
service1:
image: xxxxxx
ports:
- 8080:8080
volumes:
- xxxxxxxx
myapp:
build:
context: .
dockerfile: Dockerfile
networks:
- private
ports:
- 3000
command:
node src/app.js
Not sure if I deal right with ports in both docker files
You need to publish ports
docker run -p 3000:3000 <my image>
-p
- stands for publish
try this:
services:
myapp:
build:
context: .
dockerfile: Dockerfile
networks:
- private
ports:
- 3000:3000 ##THIS IS THE CHANGE, YOU NEED TO MAP MACHINE PORT TO CONTAINER
command:
node src/app.js
When you work with docker you must define the host for your app as 0.0.0.0
instead of localhost
.
For your express application you can define the host on app.listen
call.
Check the documentation : app.listen([port[, host[, backlog]]][, callback])
Your express code should be updated to:
const port = 3000
const host = '0.0.0.0'
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, host, () => console.log(`Example app listening on ${port}!`))
It's also important publish docker ports:
docker run -p 3000:3000 <my image>
services:
myapp:
build:
context: .
dockerfile: Dockerfile
networks:
- private
ports:
- 3000:3000
command:
node src/app.js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.