简体   繁体   中英

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

My setup is the following:

  1. Backend: Flask server running on port 5000; implemented in python
  2. Frontend: React app sending http-requests to backend
  3. Both are dockerized and running on the same node using docker-compose

My docker-compose file:

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

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

The 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;
    }
}

From the frontend I send requests to http://backend-python:5000/<my-endpoint> . backend-python is defined inside the frontend specification in docker-compose as hostname of the backend. When I run docker-compose up locally and open localhost in a browser the page gets displayed as expected. When I run docker-compose up on a Raspberry Pi 3 the frontend can't resolve http://backend-python:5000/<my-endpoint> when I open the page locally on my laptop.

I also tried to replace nginx with serving the build using serve . This leads to the same behaviour as described above.

From googling it seems to me that using docker-compose builds its own network in which each container can be found by its name or names defined under links .

Has anybody an idea why the name can't be resolved when accessing the page from an other machine?

A frontend app is running inside a browser and when the frontend app try to reach an API, it's the browser that try to communicate with it.

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.

It's why your browser can't accès to your backend using the container name, you need to expose your API and change the API/backend URL in your frontend app to use http://localhost:5000 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM