【问题标题】:Error occurred while trying to proxy request while running on Docker在 Docker 上运行时尝试代理请求时发生错误
【发布时间】:2021-05-22 14:42:55
【问题描述】:

我正在尝试将我的 React + Spring Boot 应用程序部署到 docker。但是,尽管我已经检查了 Spring Boot 服务器的端口 8080 并检查了 React 应用程序中的 proxy.js,但后端的 api 似乎没有与我的 React 应用程序连接。它不断执行“尝试代理请求时发生错误”错误。请帮我回答这个问题!

这里是 proxy.js

export default {
  dev: {
    '/api/': {
      target: 'http://localhost:8080/',
      changeOrigin: true,
      pathRewrite: {
        '^': '',
      },
    },
  }
}

这是 React App 的 dockerfile

FROM node:12

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8000
ENTRYPOINT npm run dev

后端 Dockerfile

FROM openjdk:8-jdk-alpine
EXPOSE 8080
RUN addgroup -S spring && adduser -S spring -G spring
USER spring:spring
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

还有 docker-compose.yml 文件

version: "3"

services:
  server:
    build: 
      context: ./service
      dockerfile: ./Dockerfile
    ports:
      - "8080:8080"
    image: academy-server
  client:
    build: 
      context: ./web
      dockerfile: ./Dockerfile
    ports:
      - "8000:8000"
    image: academy-client
    links: 
      - "server"

【问题讨论】:

    标签: node.js reactjs spring-boot docker docker-compose


    【解决方案1】:

    在 Docker 中运行就像在两台不同的机器上运行前端和后端一样。因此,您不能使用 localhost 与您的后端对话。相反,您需要使用 docker-compose 中定义的服务名称。因此,在您的情况下,您应该使用“服务器”而不是 localhost。

    Docker-compose 自动创建一个内部网络,将你的两个容器连接到该网络,并使用服务名称在容器之间进行路由

    【讨论】:

    • 知道了!非常感谢。我明白了这个问题
    猜你喜欢
    • 2020-07-10
    • 2019-07-09
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2020-05-06
    • 2019-10-10
    • 2021-09-25
    相关资源
    最近更新 更多