【问题标题】:Hosting web page with nginx inside docker-compose: Can't resolve hostname在 docker-compose 中使用 nginx 托管网页:无法解析主机名
【发布时间】:2020-05-01 14:40:09
【问题描述】:

我的设置如下:

  1. 后端:Flask 服务器在端口 5000 上运行;在python中实现
  2. 前端:React 应用向后端发送 http 请求
  3. 两者都是 dockerized 并使用 docker-compose 在同一节点上运行

我的 docker-compose 文件:

version: "3"
services:
  backend:
    ports:
      - "5000:5000"
    image: <backend-image>

  frontend:
    depends_on:
      - backend
    ports:
      - "80:80"
    links:
      - "backend:backend-python"
    image: <frontend-image>

nginx.conf

server {
    listen       80;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri /index.html;                 
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

我从前端向http://backend-python:5000/&lt;my-endpoint&gt; 发送请求。 backend-python 在 docker-compose 的前端规范中定义为后端的主机名。当我在本地运行 docker-compose up 并在浏览器中打开 localhost 时,页面会按预期显示。当我在 Raspberry Pi 3 上运行 docker-compose up 时,当我在笔记本电脑上本地打开页面时,前端无法解析 http://backend-python:5000/&lt;my-endpoint&gt;

我还尝试将nginx 替换为使用serve 提供构建服务。这导致与上述相同的行为。

通过谷歌搜索,在我看来,使用 docker-compose 构建了自己的网络,其中每个容器都可以通过其名称或在 links 下定义的名称找到。

有人知道为什么从其他机器访问页面时无法解析名称吗?

【问题讨论】:

  • 这是我完整的 nginx 配置。我对 nginx 很陌生,所以也许在配置中添加代理可能会解决我的问题?

标签: docker nginx networking docker-compose


【解决方案1】:

前端应用在浏览器中运行,当前端应用尝试访问 API 时,浏览器会尝试与其通信。

当您使用 nginx 在 docker 内托管前端应用程序时,容器所做的只是为浏览器所需的静态文件提供服务,但不是 nginx 尝试与您的 API 通信。

这就是为什么您的浏览器无法使用容器名称访问您的后端的原因,您需要公开您的 API 并在您的前端应用中更改 API/后端 URL 以使用 http://localhost:5000

【讨论】:

  • 这不会导致前端尝试访问我机器上的 API 而不是树莓派吗?
  • 所以为了确保访问在容器内运行的 API,我需要使用我的树莓派的 IP 在前端调用 API?
  • 是的,如果 docker 在你的浏览器之外的其他主机上运行,​​你需要使用 API 主机 IP 或 dns 名称(如果有的话)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多