使用K8S集群运行MongoDB7.0

参考:
https://hub.docker.com/_/mongo

  1. 创建PVC
    创建PVC用于数据持久化
# cat mongodb-pvc.yaml 
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mongodb-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 22Gi
  storageClassName: gluster-heketi-storageclass

创建pvc

# kubectl apply -f mongodb-pvc.yaml

查看创建的PVC

# kubectl get pvc  mongodb-pvc
NAME          STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS                  AGE
mongodb-pvc   Bound    pvc-429a856d-ebdf-11ee-b17f-525400e71cb5   22Gi       RWO            gluster-heketi-storageclass   31m
  1. 创建Deployment
# cat mongodb-deployment.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: mongodb
  name: mongodb
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: mongodb
    spec:
      containers:
      - image: mongo:7.0
        name: mongo
        ports:
        - containerPort: 27017
          protocol: TCP
        env:
        - name: MONGO_INITDB_ROOT_USERNAME
          value: "root"
        - name: MONGO_INITDB_ROOT_PASSWORD
          value: "password"
        volumeMounts:
        - mountPath: /data/db
          name: mongodb-pvc
      volumes:
      - name: mongodb-pvc
        persistentVolumeClaim:
          claimName: mongodb-pvc

注意添加以下环境变量用于鉴权,该变量名参考hub.docker.com得到

image

env:
- name: MONGO_INITDB_ROOT_USERNAME
  value: "root"
- name: MONGO_INITDB_ROOT_PASSWORD
  value: "qwer1234"

创建Deployment

# kubectl apply -f mongodb-deployment.yaml
  1. 创建Service
    把NodePort端口固定
# cat mongodb-servive.yaml 
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: mongodb
  name: mongodb
spec:
  ports:
  - port: 27017
    protocol: TCP
    targetPort: 27017
    nodePort: 47017
  selector:
    app: mongodb
  type: NodePort
status:
  loadBalancer: {}
  1. 使用NodeIP+端口访问
    下载MongoDB客户端
    下载地址
https://downloads.mongodb.com/compass/mongodb-compass-1.42.3-win32-x64.exe

使用用户名和密码连接
image

posted @ 2024-03-27 10:47  minseo  阅读(93)  评论(0编辑  收藏  举报