You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker环境下Nginx配置问题:CORS跨域错误求助

容器部署Web应用的CORS错误排查请求

我使用4个容器部署了Web应用:database、backend、frontend和nginx。已禁用主机Nginx以避免容器内Nginx被阻塞,前端页面显示正常,但提交登录请求时控制台出现以下CORS错误:

Access to fetch at 'http://127.0.0.2:8000/login' from origin 'http://server_public_address_without_ports' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local.

后端启动命令

exec gunicorn chemical_project.wsgi:application -b 127.0.0.2:8000

Nginx Docker配置

upstream backend { server backend:8000; }

server {
    listen 80;

    location /api/ {
            proxy_pass http://backend;
            #proxy_pass: http://127.0.0.2:8000
            add_header 'Access-Control-Allow-Origin' '*';
    }

    location /static/rest_framework/ {
            root /static/;
    }

    location / {
            add_header 'Access-Control-Allow-Origin' 'http://public_host_adress';
            root /var/www/frontend;
            try_files $uri $uri/ /index.html;
    }
}

Frontend构建镜像的Dockerfile

FROM node:alpine
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "run", "build"]

主docker-compose文件内容

version: '3'
services:
  db:
    image: postgres
    container_name: db
#    networks:
#      - djangonetwork
    env_file:
      - .env
    environment:
      POSTGRES_USER: *****
      POSTGRES_PASSWORD: ********
      POSTGRES_DATABASE: *****
      POSTGRES_ROOT_PASSWORD: ********
    volumes:
      - ./data:/var/lib/postgresql/data
    ports:
      - ":5432:5432"
    expose:
      - 5432
  backend:
    volumes:
      - static:/static
    env_file:
      - .env
    build:
      context: ./backend
    depends_on:
      - db
    links:
      - db:db
    ports:
      - "8000:8000"
    expose:
      - 8000

  frontend:
    build:
      context: frontend
    volumes:
      - frontend:/app/build
  nginx:
    build:
      context: ./nginx
    volumes:
      - static:/static
      - frontend:/var/www/frontend
    ports:
      - "80:80"
    expose:
      - 80
    depends_on:
      - backend
      - frontend

volumes:
  static:
  frontend:

我对容器技术不太熟悉,可能存在配置错误,恳请各位帮忙排查解决。

内容的提问来源于stack exchange,提问作者Kuba Zabielski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:06:20