如何在k8s中部署mongodb 替代本地mongodb
时间: 2023-11-25 16:50:24 浏览: 80
mongo-express-mongodb-k8s:Kubernetes配置文件,用于部署与mongodb容器通信的mongo-express容器
为在Kubernetes中部署MongoDB,可以使用StatefulSet和PersistentVolumeClaim(PVC)来创建MongoDB实例和持久化存储。下面是一个简单的MongoDB部署示例:
1.创建一个PVC以提供持久化存储:
```yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongodb-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
```
2.创建一个StatefulSet以运行MongoDB实例:
```yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongodb
spec:
serviceName: mongodb
replicas: 3
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo
ports:
- containerPort: 27017
volumeMounts:
- name: mongodb-data
mountPath: /data/db
volumes:
- name: mongodb-data
persistentVolumeClaim:
claimName: mongodb-pvc
```
3.使用kubectl apply命令应用上述两个YAML文件:
```
kubectl apply -f mongodb-pvc.yml
kubectl apply -f mongodb-statefulset.yml
```
4.验证MongoDB实例是否正在运行:
```
kubectl get statefulset mongodb
kubectl get pods -l app=mongodb
```
5.连接到MongoDB实例并插入一些数据:
```
kubectl exec -it mongodb-0 mongo
use mystore
db.foo.insert({name:'foo'})
db.foo.find()
```
阅读全文