gpt4 book ai didi

reactjs - 如何使用React和Spring Boot连接docker-compose

转载 作者:行者123 更新时间:2023-12-02 19:24:49 24 4
gpt4 key购买 nike

我有个问题。我已经创建了简单的React和Spring-Boot应用程序,并为两者创建了dockerfile。 Spring-Boot显示一些API,React对此发出请求。但是,它们都可以在端口上工作(React-3000和Spring-Boot-8080)。当我发出请求时,我的信息如下:

fetch("http://localhost:8080/projects")

为了与docker-compose一起使用,我应该如何更改它?因为当我在docker-compose文件中导出端口时,此访存请求是在容器内部而不是外部进行的。

docker 组成:
version: '3'
services:
frontend:
image: "IMAGE/FRONTEND:latest"
ports:
- "3000:3000"
depends_on:
- backend
backend:
image: "IMAGE/BACKEND:latest"
ports:
- "8080:8080"

最佳答案

这是一个docker compose的示例,它将帮助说明您如何做自己想做的事情:

version: '3'
services:
frontend:
image: "alpine:latest" #Using alpine as it has wget
command: sh -c "while true; do wget -q -S -O /dev/null http://backend:80 && sleep 4; done" #This just a sample script that get from the backend service a webpage. Note the usage of the "backend" hostname. it writes to null and only displays headers for brevity. This is just to prove that the front end can reach backend.
depends_on:
- backend
backend:
image: "nginxdemos/hello" # just a dummy image that exposes a html page over port 80
#Notice you dont need to expose ports. Look at docker compose networking for a better understanding of how these two containers are on the same n/w.

基本上像您的后端一样,我使用了niginx演示容器,该容器通过端口80提供页面。
对于前端,我使用了一个shell脚本,该脚本仅查询后端并仅显示标题。

因此,在您的情况下,问题在于您的前端尝试使用 localhost作为后端。而本地主机只是指向前端容器。您确实希望它指向主机名 backend,该主机名随后将把您路由到后端服务中的容器。

要了解码合网络的工作原理,请查看 https://docs.docker.com/compose/networking/
在以上示例中起作用的相关代码段。

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

关于reactjs - 如何使用React和Spring Boot连接docker-compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57061419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com