Nodejs API请求与Reactjs应用程序和Nginx之间的问题

ylamdve6  于 2022-11-02  发布在  Nginx
关注(0)|答案(1)|浏览(145)

我正在开发一个全栈应用程序,其中的前端是用Reactjs制作的,并且在nodejs中有一个通过API(express)请求的应用程序。为了使前端对用户可用,我使用Nginx服务。
我正在Ubuntu Docker容器中编译整个应用程序,以便稍后在Google Cloud Run上部署。到目前为止,我设法使网站的前端在我的容器的端口80上可用,我可以通过链接http://localhost:80在浏览器中访问它。
但是,React应用程序无法向nodejs中的API发出请求,我在下面的图像中看到了错误:

但是,当我在容器中运行相同的请求命令(curl http://0.0.0.0:5555/getDocuments?col=houses_test)(通过docker run -it)时,我得到了预期的响应,没有错误。
这是我的项目树

📦My-Project
 ┣ 📂backend
 ┃ ┣ 📂node_modules
 ┃ ┣ 📜index.js
 ┃ ┣ 📜package-lock.json
 ┃ ┗ 📜package.json
 ┣ 📂frontend
 ┃ ┣ 📂build
 ┃ ┣ 📂node_modules
 ┃ ┣ 📂public
 ┃ ┣ 📂src
 ┃ ┣ 📜package.json
 ┃ ┗ 📜yarn.lock
 ┣ 📜Dockerfile
 ┗ 📜nginx.conf

下面是我的Dockerfile


# Image definition

FROM ubuntu:20.04
WORKDIR /app

# Dependencies installation

RUN apt update -y
RUN apt install curl gnupg systemctl -y

# Nodejs installation

RUN curl -sL https://deb.nodesource.com/setup_14.x | bash -
RUN apt update -y && apt install nodejs -y

# Yarn installation

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN apt update -y && apt install yarn -y

# Backend build

COPY backend/package.json ./backend/
RUN cd backend && npm i
COPY ./backend/ ./backend/

# Frontend build

COPY frontend/package.json ./frontend/
RUN cd frontend && yarn install --frozen-lockfile
COPY ./frontend/ ./frontend/
RUN cd frontend && yarn build

# Nginx installation and config

RUN 134 | 2 | apt install nginx -y
RUN mkdir /var/www/127.0.0.1
RUN chmod 755 -R /var/www/127.0.0.1/
COPY ./nginx.conf /etc/nginx/sites-available/127.0.0.1
RUN unlink /etc/nginx/sites-enabled/default
RUN ln -s /etc/nginx/sites-available/127.0.0.1 /etc/nginx/sites-enabled/
RUN cp -r frontend/build/* /var/www/127.0.0.1
CMD ["systemctl" "start" "nginx"]

这是我的nginx.conf

server{
    listen 80;
    listen [::]:80;

    root /var/www/127.0.0.1;
    index index.html;
}

我在React中为API请求提供服务:

import axios from 'axios'

export default axios.create({
    baseURL: `http://0.0.0.0:5555`
})

我真的很感激你的帮助!

ma8fv8wu

ma8fv8wu1#

您的Dockerfile缺少应用程序端口为(80)的EXPOSEEXPOSE指令通知Docker容器在运行时侦听指定的网络端口
Docker文档官方链接https://docs.docker.com/engine/reference/builder/#expose
示例:

EXPOSE 80

相关问题