如何在本地访问Docker容器应用程序? [英] How to access Docker container app on local?

查看:106
本文介绍了如何在本地访问Docker容器应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Node.js/Express应用程序:

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}!`))

当我像这样启动它时,它可以正常工作:node src/app.js

It works fine when I start it like: node src/app.js

现在,我正在尝试在Docker容器中运行它.Dockerfile是:

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" ]

一切正常: docker run< my image>:

Listening on port 3000

但是现在我无法在浏览器中访问它: http://localhost:3000

But now I cannot access it in my browser: http://localhost:3000

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

如果我尝试在docker-compose中运行它,也会发生同样的情况:

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

不确定我是否正确处理两个docker文件中的端口

Not sure if I deal right with ports in both docker files

推荐答案

尝试一下:

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

这篇关于如何在本地访问Docker容器应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆