[英]Docker compose networking issue with react app
I am running a react app and a json server with docker-compose.我正在运行一个反应应用程序和一个 json 服务器与 docker-compose。
Usually I connect to the json server from my react app by the following:通常我通过以下方式从我的反应应用程序连接到 json 服务器:
fetch('localhost:8080/classes')
.then(response => response.json())
.then(classes => this.setState({classlist:classes}));
Here is my docker-compose file:这是我的 docker-compose 文件:
version: "3"
services:
frontend:
container_name: react_app
build:
context: ./client
dockerfile: Dockerfile
image: praventz/react_app
ports:
- "3000:3000"
volumes:
- ./client:/usr/src/app
backend:
container_name: json_server
build:
context: ./server
dockerfile: Dockerfile
image: praventz/json_server
ports:
- "8080:8080"
volumes:
- ./server:/usr/src/app
the problem is I can't seem to get my react app to fetch this information from the json server.问题是我似乎无法让我的反应应用程序从 json 服务器获取此信息。
on my local machine I use 192.168.99.100:3000 to see my react app在我的本地机器上,我使用 192.168.99.100:3000 来查看我的反应应用程序
and I use 192.168.99.100:8080 to see the json server but I can't seem to connect them with any of the following:我使用 192.168.99.100:8080 查看 json 服务器,但我似乎无法将它们与以下任何一个连接:
backend:8080/classes
json_server:8080/classes
backend/classes
json_server/classes
{host:"json_server/classes", port:8080}
{host:"backend/classes", port:8080}
Both the react app and the json server are running perfectly fine independently with docker-compose up. React 应用程序和 json 服务器都可以在 docker-compose 上独立运行。
What should I be putting in fetch()?我应该在 fetch() 中放入什么?
Remember that the React application always runs in some user's browser;请记住,React 应用程序总是在某些用户的浏览器中运行; it has no idea that Docker is involved, and can't reach or use any of the Docker-related networking setup.
它不知道涉及到 Docker,并且无法访问或使用任何与 Docker 相关的网络设置。
on my local machine I use [...] 192.168.99.100:8080 to see the json server
在我的本地机器上,我使用 [...] 192.168.99.100:8080 查看 json 服务器
Then that's what you need in your React application too.那么这也是你在 React 应用程序中所需要的。
You might consider setting up some sort of proxy in front of this that can, for example, forward URL paths beginning with /api
to the backend container and forward other URLs to the frontend container (or better still, run a tool like Webpack to compile your React application to static files and serve that directly).您可以考虑在此之前设置某种代理,例如,将以
/api
开头的 URL 路径转发到后端容器,并将其他 URL 转发到前端容器(或者更好的是,运行 Webpack 之类的工具进行编译您的 React 应用程序到 static 文件并直接提供)。 If you have that setup, then the React application can use a path /api/v1/...
with no host, and it will be resolved relative to whatever the browser thinks "the current host" is, which should usually be the proxy.如果你有这样的设置,那么 React 应用程序可以使用没有主机的路径
/api/v1/...
,它将相对于浏览器认为“当前主机”的任何内容进行解析,通常应该是代理.
You have two solutions:你有两个解决方案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.