Docker Compose中前端容器无法解析后端服务名称问题求助
问题分析与解决方案
核心问题1:前端请求地址的Docker网络误解
你踩了DevOps新手常见的坑:React代码是在用户浏览器中执行的,而非前端容器内部。浏览器无法识别Docker Compose内部的服务名backend,它只会使用宿主机的DNS解析地址,所以你配置的REACT_APP_BACKEND_URL=http://backend:3000在浏览器环境下完全无法访问。
核心问题2:CORS Origin不匹配
后端配置的CORS_ORIGIN=http://frontend:3001是Docker内部的服务地址,但浏览器实际访问前端的地址是http://localhost:3001,两者不匹配导致CORS校验失败,出现你看到的类似CORS的错误。
快速修复方案
直接修改docker-compose.yaml中的环境变量,让前端请求宿主机映射的后端端口,同时修正CORS允许的Origin:
version: "3" services: frontend: build: ./frontend image: hello-world-frontend:latest ports: - "3001:3000" environment: # 改为宿主机可访问的后端地址 - REACT_APP_BACKEND_URL=http://localhost:3000 depends_on: - backend networks: - internal backend: build: ./backend image: hello-world-backend:v1.0.0 ports: - "3000:3000" environment: # 改为浏览器实际访问的前端地址 - CORS_ORIGIN=http://localhost:3001 networks: - internal networks: internal: driver: bridge
重启服务生效:
docker-compose down && docker-compose up --build
进阶方案:反向代理消除CORS(更贴近生产环境)
如果不想依赖CORS配置,可以添加Nginx反向代理服务,让前后端请求都通过Nginx转发,实现同域访问:
- 创建
nginx.conf配置文件:
server { listen 80; # 转发前端静态文件请求 location / { proxy_pass http://frontend:3000; } # 转发后端API请求 location /api { proxy_pass http://backend:3000/; } }
- 修改
docker-compose.yaml添加Nginx服务:
version: "3" services: frontend: build: ./frontend image: hello-world-frontend:latest environment: # 前端请求同域的/api路径 - REACT_APP_BACKEND_URL=/api depends_on: - backend networks: - internal backend: build: ./backend image: hello-world-backend:v1.0.0 networks: - internal nginx: image: nginx:alpine ports: - "8080:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf depends_on: - frontend - backend networks: - internal networks: internal: driver: bridge
- 调整
App.js中的请求路径(适配同域/api转发):
const response = await fetch(`${backendURL}`); // 移除末尾的/,因为Nginx已转发到后端根路径
之后浏览器访问http://localhost:8080即可,所有请求均为同域,无需配置CORS。
内容的提问来源于stack exchange,提问作者Milo
相关产品推荐
相关产品推荐

