Docker化React应用无法与Docker化Django应用通信问题排查
问题
我用自签名证书通过sslserver搭建了运行在https://localhost:8000的Django应用,同时搭建了使用自签名证书、运行在https://localhost:3000的React应用。本地终端直接运行两者时,能正常运行并互相通信;但通过Docker Desktop运行时,前端向后端发起请求返回代理错误:
2024-01-12 21:43:00 Proxy error: Could not proxy request /main.dd206638be0188052640.hot-update.json from localhost:3000 to https://localhost:8000/.
注:用Postman调用后端可正常运行。
相关配置
Django settings.py
ALLOWED_HOSTS = [ 'localhost' # Provide the host that the server allows. ] # Config for CORS-Headers. CORS_ALLOWED_ORIGINS = [ # Provide frontend address. "https://localhost:3000" ]
React package.json
"proxy": "https://localhost:8000",
docker-compose.yml
version: '3.10' services: django-backend: container_name: proxmox-project-backend build: context: ./django-backend dockerfile: Dockerfile image: django-backend:0.0.1 ports: - '8000:8000' react-frontend: container_name: proxmox-project-frontend build: context: ./react-frontend dockerfile: Dockerfile image: react-frontend:0.0.1 ports: - '3000:3000' stdin_open: true tty: true environment: - HTTPS=true - SSL_CRT_FILE=/app/ssl/react.crt - SSL_KEY_FILE=/app/ssl/react.key
解决方案
1. 修正容器间网络访问地址
Docker容器内的localhost指向容器自身,而非宿主机。前端容器请求https://localhost:8000会访问自身的8000端口,而非后端容器。
修改React的代理配置,使用Docker Compose中定义的后端服务名作为地址:
- 将package.json中的
proxy字段改为:"proxy": "https://django-backend:8000"
2. 更新Django的访问控制配置
后端容器需要允许来自前端服务名和宿主机的请求:
- 修改settings.py的
ALLOWED_HOSTS,添加后端服务名:ALLOWED_HOSTS = [ 'localhost', 'django-backend' ] - 更新
CORS_ALLOWED_ORIGINS,同时允许前端容器地址和宿主机前端地址:CORS_ALLOWED_ORIGINS = [ "https://localhost:3000", "https://react-frontend:3000" ]
3. 处理自签名证书信任问题
前端容器默认不信任自签名证书,可通过两种方式解决:
方式一:开发环境临时跳过验证(不建议生产用)
在docker-compose.yml的react-frontend服务环境变量中添加:
- NODE_TLS_REJECT_UNAUTHORIZED=0
方式二:导入后端证书到信任列表(推荐)
- 将后端的自签名证书
django.crt复制到前端项目的ssl目录 - 在前端Dockerfile中添加以下命令导入证书:
COPY ssl/django.crt /usr/local/share/ca-certificates/django.crt RUN update-ca-certificates
4. 重启容器应用配置
执行以下命令重新构建并启动容器:
docker-compose down docker-compose up --build
内容的提问来源于stack exchange,提问作者John Dinos
相关产品推荐
相关产品推荐

