编写service的文件:

[root@k8s-master-1 mongodb]# vim service.yaml

apiVersion: v1

kind: Service

metadata:

name: mongo

labels:

name: mongo

spec:

type: NodePort

ports:

- port: 27017

targetPort: 27017

nodePort: 32000

selector:

role: mongo

编写启动容器的yaml文件:

[root@k8s-master-1 mongodb]# vim statefulset.yaml

apiVersion: apps/v1beta1

kind: StatefulSet

metadata:

name: mongo

spec:

serviceName: "mongo"

replicas: 3

template:

metadata:

labels:

role: mongo

environment: test

spec:

terminationGracePeriodSeconds: 10

containers:

- name: mongo

image: mongo

command:

- mongod

- "--replSet"

- rs0

- "--bind_ip"

- 0.0.0.0

ports:

- containerPort: 27017

volumeMounts:

- name: mongo

mountPath: /data/db

- name: mongo-sidecar

image: cvallance/mongo-k8s-sidecar

env:

- name: MONGO_SIDECAR_POD_LABELS

value: "role=mongo,environment=test"

volumeClaimTemplates:

- metadata:

name: mongo

annotations:

volume.beta.kubernetes.io/storage-class: "nfs-storage"

spec:

accessModes: [ "ReadWriteOnce" ]

storageClassName: "nfs-storage"

resources:

requests:

storage: 10Gi

编写存储的yaml文件:

[root@k8s-master-1 mongodb]# vim pv.yaml

apiVersion: v1

kind: PersistentVolumeClaim

metadata:

name: mongo

namespace: default

spec:

accessModes:

- ReadWriteOnce

resources:

requests:

storage: "1G"

volumeName:

storageClassName: nfs-storage

 

初始化MongDB集群

得到统一服务(Service)的IP地址:

[root@k8s-master-1 mongodb]# kubectl get svc mongo

获取mongo节点的具体IP:

[root@k8s-master-1 mongodb]# kubectl describe svc/mongo

查看mongo容器名:

[root@k8s-master-1 mongodb]# kubectl get pods

进入容器,进入mongo:

[root@k8s-master-1 mongodb]# kubectl exec -it mongo-0 bash

root@mongo-0:/# mongo --host 172.30.49.18

把各个mongo节点加入集群:

root@mongo-0:/# config = {_id: 'rs0', members: [{_id: 0, host: '172.30.49.18:27017',priority:4},{_id: 1, host: '172.30.50.14:27017',priority:3},{_id: 2, host: '172.30.93.14:27017',priority:3}]}

初始化:

rs0:PRIMARY> rs.reconfig(config,{"force": true})

查看集群是否加入成功:

rs0:PRIMARY> rs.status()

 

还可以通过如下命令添加或删除已经加入replica set集群的节点

rs.add("172.16.7.3")  #添加节点的IP

rs.remove("172.16.7.3:27017")  #删除节点的IP和端口

 

 

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐