同一个docker-compose中,Nextjs服务器组件如何请求后端数据?

问题描述 投票:0回答:1

如标题所示,我的前端Nextjs项目、后端Django和Nginx都配置在同一个docker-compose.yml中。现在的问题是如何在前端服务器组件中请求后端数据。我尝试过各种以“/api/v1/”为核心的URL,但都不起作用。

实在是看不懂,应该是个很简单的问题但是我尝试了很久还是解决不了。

docker-compose 配置:

version: '3'
services:

  client:
    build:
      context: ./journey-journal-frontend
      dockerfile: Dockerfile
    environment:
      - NEXT_PUBLIC_BACKEND_URL=http://server:8000
    volumes:
      - app-volume:/app/.next
    user: "nextjs"
    depends_on:
      - server

  server:
    build:
      context: ./journey-journal-manage/admin_panel
      dockerfile: Dockerfile
    volumes:
      - static_volume:/usr/src/app/staticfiles
    ports:
      - 8000:8000

  nginx:
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - 80:80
    volumes:
      - static_volume:/usr/src/app/staticfiles
    depends_on:
      - client
      - server

volumes:
  app-volume:
  static_volume:

nginx配置:

  server {
        listen 80;

        location / {
            proxy_pass http://client:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }

        location /api {
            proxy_pass http://server:8000;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For;                                   $proxy_add_x_forwarded_for;
        }

        location /admin {
            proxy_pass http://server:8000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }

        location /static/ {
            alias /usr/src/app/staticfiles/;
        }
    }

前端配置:

  const api = axios.create({
  baseURL: `/api/v1/`, // 设置 baseURL
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
});

希望有经验的人可以告诉我如何解决这个问题,我将非常感激

docker nginx next.js docker-compose
1个回答
0
投票

我知道这个问题的原因,因为请求数据是在Nextjs前端项目的服务器组件中进行的,该组件会在镜像编译阶段拉取数据。此时docker-compose中的服务器还没有启动,所以当然无法获取到数据。只有所有服务都构建并启动后,才能访问其他服务。

© www.soinside.com 2019 - 2024. All rights reserved.