簡體   English   中英

在 docker-compose 內使用 nginx 托管 web 頁面:無法解析主機名

[英]Hosting web page with nginx inside docker-compose: Can't resolve hostname

我的設置如下:

  1. 后端:Flask 服務器運行在 5000 端口; 在 python 中實現
  2. 前端:React 應用程序向后端發送 http 請求
  3. 兩者都使用 docker-compose 進行了 dockerized 並在同一節點上運行

我的 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/<my-endpoint>發送請求。 backend-python在 docker-compose 的前端規范中定義為后端的主機名。 當我在本地運行docker-compose up並在瀏覽器中打開localhost時,頁面會按預期顯示。 當我在 Raspberry Pi 3 上運行docker-compose up ,當我在筆記本電腦上本地打開頁面時,前端無法解析http://backend-python:5000/<my-endpoint>

我還嘗試將nginx替換為使用serve服務構建。 這導致與上述相同的行為。

從谷歌搜索來看,在我看來,使用 docker-compose 構建了自己的網絡,其中每個容器都可以通過其名稱或在links下定義的名稱找到。

有人知道為什么從其他機器訪問頁面時無法解析名稱嗎?

前端應用程序在瀏覽器中運行,當前端應用程序嘗試訪問 API 時,是瀏覽器嘗試與之通信。

When you host a frontend app inside docker with nginx, all the container do is to server the static file needed by the browser, but it's not nginx that try to communicate with your API.

這就是為什么您的瀏覽器無法使用容器名稱訪問您的后端的原因,您需要公開您的 API 並在您的前端應用程序中更改 API/后端 URL 以使用http://localhost:5000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM