如何通过 docker-compose 网络将前端连接到后端

Kea*_*nu 7 docker dockerfile docker-compose

我正在尝试对我的 Angular + Express 应用程序进行 dockerize。我有一个创建两个容器的 docker-compose 文件,并且我能够从我的主机(使用我的浏览器)访问这些容器,但是每当我尝试从 http 访问后端时,我只会得到一个“ERR_NAME_NOT_RESOLVED”我的前端提出的请求。

我已经查过这个问题,似乎大多数人都建议服务名称和容器端口应该足以在同一网络上时击中另一个容器。我尝试点击“ http://express:8000/user?user=030f0e70-9a8f-11e9-b5d1-f5cb6c0f3616 ”,鉴于我从其他地方看到的情况,我认为这应该有效,但无论如何,我得到了同样的错误。

我的 docker-compose 文件看起来像

version: '3' # specify docker-compose version

# Define the services/containers to be run
services:
  angular: # name of the first service
    build: ./ # specify the directory of the Dockerfile
    ports:
      - "4200:80" # specify port forewarding
    links:
      - "express"
    depends_on:
      - "express"

  express: #name of the second service
    build:  # specify the directory of the Dockerfile
      context: ./
      dockerfile: dockerfile.be
    ports:
      - "8000:8000" #specify ports forewarding
    expose:
      - "8000"
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望我的前端能够通过设置的端点访问另一个容器,这样我就可以通过最小的更改来部署应用程序。我将不胜感激任何建议。我觉得我错过了一些非常简单的东西,但经过几个小时的修补,我仍然没有抓住它。

谢谢!

atl*_*ine 3

事实上你的流量如下:

  1. 用户浏览器向 请求页面angular container,然后所有页面将呈现到用户的浏览器。

  2. 前面的 javascript 代码用于angular HttpClientexpress container.

    当时,虽然docker-compose为你设置了一个定制的网络,提供自动dns来解析angularexpress但这个dns只在容器之间起作用,对主机不起作用。

    但是,您的augular HttpClientwhich 调用http://express发生在用户的浏览器上,而不是在容器中,因此自动 DNS 肯定无法为您解析名称express

对于你来说,如果你只想从你的docker主机打开浏览器,你可以使用localhost,但如果你还希望其他机器的用户访问你的网站,你必须使用你的docker主机的ip。

然后,angular HttpClient你需要使用像http://your_dockerhost_ip:8000访问快递集装箱这样的东西。

有兴趣的话可以访问这个看看User-defined bridges provide automatic DNS resolution between containers

  • 因为容器在同一主机上运行,​​所以我能够将我的角度前端的所有请求定位到“http://”+ location.hostname +“:8000”,这对于实际到达后端是有效的。谢谢您的帮助! (2认同)