我有一个 mern 堆栈应用程序(react vite + nodejs)Web 应用程序运行良好,因为我启用了 cors 中间件以允许我的前端向后端发送请求,但问题是当我尝试在 minikube(deployment-frontend + deploy-backend)上部署该堆栈时,我收到了跨源错误,尽管它在我的源代码中配置正确,并且无需部署即可正常工作。我不知道问题的原因是什么,即使当我使用 docker compose 来测试 dockerfiles 和整个堆栈时它也运行良好,但问题出现在 minikube 中。
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 1
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: frontend
image: achref2h/frontend:v2
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: frontend
spec:
selector:
app: frontend
ports:
- protocol: TCP
port: 80
targetPort: 80
type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
spec:
replicas: 1
selector:
matchLabels:
app: backend
template:
metadata:
labels:
app: backend
spec:
containers:
- name: backend
image: achref2h/backend:v1
ports:
- containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: backend
spec:
selector:
app: backend
ports:
- protocol: TCP
port: 3000
targetPort: 3000
前端 Dockerfile:
FROM node:20 as builder
WORKDIR /frontend
COPY package*.json ./
RUN npm i
COPY . .
RUN npm run build
FROM ubuntu
RUN apt-get update
RUN apt-get install nginx -y
COPY --from=builder /frontend/dist /var/www/html/
EXPOSE 80
CMD ["nginx","-g","daemon off;"]
后端 Dockerfile:
FROM node:lts AS builder
WORKDIR /api
COPY package*.json ./
RUN npm install
COPY . ./
RUN npm run build
FROM node:lts-slim
WORKDIR /api
COPY --from=builder /api/ ./
RUN npm install --only=production
EXPOSE 3000
CMD ["node", "./dist/index.js"]
笔记 :
- 为了测试目的,这是一个简单的 mern 应用程序,不需要数据库,只需前端向后端发送两个简单的请求
- 前端托管在 nginx 的 80 端口上,后端运行在 3000 端口上。提前致谢!