在单个域上为React应用(React app)和Express后端设置Kubernetes(k8s)入口,通常涉及以下几个步骤:
当你的React应用和Express后端部署在同一个Kubernetes集群中,并且希望它们可以通过同一个域名访问时,可以使用Ingress来设置入口。
以下是一个基本的示例,展示如何在Kubernetes中设置Ingress来管理React和Express服务。
首先,确保你的React应用已经构建完成,并且有一个Docker镜像。然后创建一个Kubernetes Deployment和Service。
# react-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: react-app
spec:
replicas: 3
selector:
matchLabels:
app: react-app
template:
metadata:
labels:
app: react-app
spec:
containers:
- name: react-app
image: your-react-image:tag
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: react-service
spec:
selector:
app: react-app
ports:
- protocol: TCP
port: 80
targetPort: 80
同样,确保你的Express应用已经构建完成,并且有一个Docker镜像。然后创建一个Kubernetes Deployment和Service。
# express-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: express-app
spec:
replicas: 3
selector:
matchLabels:
app: express-app
template:
metadata:
labels:
app: express-app
spec:
containers:
- name: express-app
image: your-express-image:tag
ports:
- containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: express-service
spec:
selector:
app: express-app
ports:
- protocol: TCP
port: 80
targetPort: 3000
创建一个Ingress资源来管理React和Express服务的访问。
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: yourdomain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: react-service
port:
number: 80
- path: /api/
pathType: Prefix
backend:
service:
name: express-service
port:
number: 80
使用kubectl
命令应用上述配置文件:
kubectl apply -f react-deployment.yaml
kubectl apply -f express-deployment.yaml
kubectl apply -f ingress.yaml
通过以上步骤,你应该能够在单个域上为React应用和Express后端设置Kubernetes入口。
领取专属 10元无门槛券
手把手带您无忧上云