运行React App的Docker容器中的Proxying API请求 [英] Proxying API Requests in Docker Container running react app

查看:90
本文介绍了运行React App的Docker容器中的Proxying API请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在docker容器中运行一个简单的react应用。在开发过程中,我使用 package.json 中的代理密钥来指定我的后端api网址: proxy: http:// localhost: 5000

I'm running a simple react app in a docker container. During development I'm using the proxy key in package.json to specify my backend api url: "proxy": "http://localhost:5000"

当我在本地运行 npm start 时,一切正常。但是,当我在Docker容器内 npm start 时,它指向 http:// localhost:3000 。我也尝试过手动设置代理,如下面的Dockerfile所示,但似乎无济于事:

Everything works fine when I run npm start locally. However, when I npm start inside a docker container it's pointing to "http://localhost:3000". I'm tried setting the proxy manually as well, as demonstrated by my Dockerfile below, but nothing seems to work:

FROM node:13-alpine
WORKDIR /app

# install dependencies
COPY package*.json ./
RUN npm install --silent

# copy source code
COPY src/ ./src/
COPY public/ ./public/

RUN npm config set proxy http://localhost:5000  # set manully
CMD ["npm", "start"]

我做错了还是

推荐答案

在docker中运行应用程序时,需要将端口设置为后端服务而不是localhost。例如,检查以下Docker容器及其服务。我们的前端运行在端口 3000 中,后端运行在端口 5000 中。因此,将localhost替换为 proxy: http:// backend:5000

You need to set the port to your backend service instead of localhost while running the app in docker. Check the following docker container and it's services for example. We have the frontend running in port 3000 and backend running in port 5000. So, replace localhost with "proxy": "http://backend:5000"

version: '3'

services:
  backend:
    build: ./backend
    ports:
      - 5000:5000
  frontend:
    build: ./frontend
    ports:
      - 3000:3000
    links:
      - backend
    command: npm start

这篇关于运行React App的Docker容器中的Proxying API请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆