简体   繁体   English

如何在本地访问Docker容器应用程序?

[英]How to access Docker container app on local?

I have a simple Node.js/Express app: 我有一个简单的Node.js / Express应用程序:

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 当我启动它时,它工作正常:node src / app.js

Now I'm trying to run it in a Docker container. 现在我试图在Docker容器中运行它。 Dockerfile is: Dockerfile是:

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>: 它开始很好: docker run <my image>:

Listening on port 3000

But now I cannot access it in my browser: http://localhost:3000 但现在我无法在浏览器中访问它: http:// localhost:3000

This site can’t be reached localhost refused to connect.

Same happen if I try to run it within docker-compose: 如果我尝试在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 不确定我是否正确处理两个docker文件中的端口

You need to publish ports 您需要发布端口

docker run -p 3000:3000 <my image>

-p - stands for publish -p - 代表发布

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 . 使用docker时,必须将应用程序的主机定义为0.0.0.0而不是localhost

For your express application you can define the host on app.listen call. 对于您的快速应用程序,您可以在app.listen调用上定义主机。

Check the documentation : app.listen([port[, host[, backlog]]][, callback]) 检查文档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端口也很重要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM