ReactJS 浏览器应用程序无法看到 Docker Compose 网络中的内容 [英] ReactJS browser app cannot see things in the Docker Compose network
问题描述
我有一个带有自己的 Dockerfile 的 ReactJS 项目,暴露了端口 3000:3000.
I have a ReactJS project with its own Dockerfile, exposing port 3000:3000.
我还有一个 PHP 项目,它有自己的 Dockerfile,暴露了 80:80 端口.PHP 应用程序还包含 MySQL、Redis 和 Nginx 的容器
I also have a PHP project with its own Dockerfile, exposing port 80:80. The PHP app also has containers for MySQL, Redis and Nginx
对于 PHP 应用程序,我有一个 docker-compose 文件,它为 PHP、Nginx、MySQL 和 Redis 创建一个网络 (my-net
) 以进行通信.但是,我现在希望 ReactJS(在一个单独的项目中)能够与 PHP 应用程序通信.
For the PHP app, I have a docker-compose file that creates a network (my-net
) for PHP, Nginx, MySQL and Redis to communicate on. However, I now want the ReactJS (which is in a separate project) to be able to communicate with the PHP app.
我在 React 项目中添加了一个 docker-compose 文件,并将其从 PHP 项目 my-net
添加到网络,并声明为 external
以便它不会尝试创建它.
I added a docker-compose file to the React project, and added it to the network from the PHP project my-net
and declared it as external
so that it doesn't try to create it.
这似乎有效:从 ReactJS 容器,我可以 ping app
(我的后端服务的名称)并且它正常工作.但是,从 ReactJS 代码来看,如果我使用诸如 axios
之类的东西来尝试访问后端 API,则它无法解析 app
或 http://app
或任何变体.但是,如果我将其替换到 axios
中,它可以访问底层 IP 地址.
This seems to work: From the ReactJS container, I can ping app
(the name of my backend service) and it works properly. However, from the ReactJS code, if I use something like axios
to try and hit the backend API, it can't resolve app
or http://app
or any variation. It can however access the underlying IP address if I substitute that into in axios
.
所以主机名解析似乎存在一些问题,大概是在 axios
/JavaScript 端.是否有我遗漏的东西或无法正常工作的原因?
So there seems to be some issue with the hostname resolution, and presumably this is on the axios
/ JavaScript end. is there something I'm missing or a reason this isn't working?
推荐答案
当 JavaScript 在浏览器中运行时(在 Docker 之外)你不能使用 app
因为它只在 Docker 网络内部可用(通过嵌入式 DNS 服务器).
When the JavaScript runs in a browser (outside of Docker) you can not use app
because that is only available inside the Docker network (via the embedded DNS server).
要从外部访问 PHP 服务器,请改用 localhost 和暴露的端口 (80).
To access your PHP server from outside use localhost and the exposed port (80) instead.
这篇关于ReactJS 浏览器应用程序无法看到 Docker Compose 网络中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!