在docker容器中运行时,nodejs app不会连接到localhost

pel*_*can 0 docker dockerfile docker-compose docker-swarm docker-machine

My environment:
Ubunut 17.04 LTS
npm --version: 5.6.0
nodejs --version: 4.7.2
angular cli version: 1.6.4
Run Code Online (Sandbox Code Playgroud)

docker-compose文件:

version: '3'

services:
 my-app:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    volumes:
      - .:/usr/src/app
    ports:
      - "4200:4200"
Run Code Online (Sandbox Code Playgroud)

我在dockerfile中注释掉了EXPOSE 4200,因为我已经从docker-compose.yml文件中安装了它,是不是没问题,我应该在dockerfile中公开并在docker-compose中挂载?

在命令行上运行npm start会在浏览器上成功启动应用程序,因为我可以去localhost:4200看看应用程序是否正在运行.

但是,如果我使用docker构建我的应用程序并运行docker-compose,我看到nodejs服务器仍在运行localhost:4200,但是,我无法访问该应用程序,因此localhost:4200无法启动该页面.

运行APP手动工作很棒,我可以在浏览器上看到它:

ubuntu17@ubuntu17:~/playground/apps/myapp-ui$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2018-01-16T16:22:51.912Z                                                          
Hash: 40ac2bd0588ee2136d15
Time: 13963ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 275 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 559 kB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 514 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 12.1 MB [initial] [rendered]

webpack: Compiled successfully.
Run Code Online (Sandbox Code Playgroud)

从DOCKER-COMPOSE运行应用程序运行精细但我无法使用localhost在浏览器上看到应用程序:4200

并且从码头工人组成

ubuntu17@ubuntu17:~/playground/apps/my-app-ui$ docker-compose up 
Creating network "my-app_default" with the default driver
Creating my-app_my-app_1 ... done
Attaching to my-app_my-app_1
my-app_1  | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
my-app_1  | Date: 2018-01-16T16:28:05.444Z
my-app_1  | Hash: 40ac2bd0588ee2136d15
my-app_1  | Time: 13584ms
my-app_1  | chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
my-app_1  | chunk {main} main.bundle.js (main) 271 kB [initial] [rendered]
my-app_1  | chunk {polyfills} polyfills.bundle.js (polyfills) 549 kB [initial] [rendered]
my-app_1  | chunk {styles} styles.bundle.js (styles) 511 kB [initial] [rendered]
my-app_1  | chunk {vendor} vendor.bundle.js (vendor) 12.1 MB [initial] [rendered]
my-app_1  | 
my-app_1  | webpack: Compiled successfully.
Run Code Online (Sandbox Code Playgroud)

whi*_*s11 6

好的,正如您在问题中所说,您的流程正在监听连接localhost:4200.

在docker容器内,localhost是容器本身的loopback设备的地址,该地址是分开的,无法从主机网络访问.

您需要编辑节点进程,以便通过编辑Dockerfile中的入口点来监听所有地址,如下所示:

ENTRYPOINT ["ng", "serve", "-H", "0.0.0.0"]
Run Code Online (Sandbox Code Playgroud)