How to access Docker container app on local?

爱⌒轻易说出口 提交于 2021-01-28 11:30:23

问题


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


回答1:


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



回答2:


You need to publish ports

docker run -p 3000:3000 <my image>

-p - stands for publish




回答3:


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:

  • Running docker: docker run -p 3000:3000 <my image>
  • Running docker-compose:
services:
  myapp:
    build: 
      context: .
      dockerfile: Dockerfile
    networks:
      - private
    ports:
      - 3000:3000
    command:
      node src/app.js


来源:https://stackoverflow.com/questions/56484240/how-to-access-docker-container-app-on-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!