# Helm 安装 MongoDB-副本集群







```bash
helm repo add stable https://kubernetes.oss-cn-hangzhou.aliyuncs.com/charts
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
```

### 副本集群,一主多从,故障自动转移

```bash
helm upgrade --install mongodb-replicaset bitnami/mongodb --version 16.4.4 \
--namespace demo --create-namespace \
--set architecture=replicaset \
--set replicaCount=3 \
--set auth.enabled=true \
--set auth.rootUser=root \
--set auth.rootPassword=root \
--set auth.usernames[0]=admin \
--set auth.passwords[0]=123456 \
--set auth.databases[0]=kline_dev \
--set persistence.enabled=false \
--set externalAccess.enabled=true \
--set externalAccess.service.type=NodePort \
--set externalAccess.service.nodePorts[0]=31111 \
--set externalAccess.service.nodePorts[1]=31112 \
--set externalAccess.service.nodePorts[2]=31113
```

```bash
# 内网地址
mongodb-cluster-0.mongodb-cluster-headless.demo.svc.cluster.local:27017
mongodb-cluster-1.mongodb-cluster-headless.demo.svc.cluster.local:27017
mongodb-cluster-2.mongodb-cluster-headless.demo.svc.cluster.local:27017


# root 账户密码
export MONGODB_ROOT_PASSWORD=$(kubectl get secret --namespace demo mongodb-cluster -o jsonpath="{.data.mongodb-root-password}" | base64 -d)
export MONGODB_PASSWORD=$(kubectl get secret --namespace demo mongodb-cluster -o jsonpath="{.data.mongodb-passwords}" | base64 -d | awk -F',' '{print $1}')


# 临时客户端
kubectl run --namespace demo mongodb-cluster-client --rm --tty -i --restart='Never' --env="MONGODB_ROOT_PASSWORD=$MONGODB_ROOT_PASSWORD" --image docker.io/bitnami/mongodb:8.0.4-debian-12-r3 --command -- bash

# 测试连接
mongosh admin --host "mongodb-cluster-0.mongodb-cluster-headless.demo.svc.cluster.local:27017,mongodb-cluster-1.mongodb-cluster-headless.demo.svc.cluster.local:27017,mongodb-cluster-2.mongodb-cluster-headless.demo.svc.cluster.local:27017" --authenticationDatabase admin -u $MONGODB_ROOT_USER -p $MONGODB_ROOT_PASSWORD


# 获取开放端口
echo "$(kubectl get svc --namespace demo -l "app.kubernetes.io/name=mongodb,app.kubernetes.io/instance=mongodb-cluster,app.kubernetes.io/component=mongodb,pod" -o jsonpath='{.items[*].spec.ports[0].nodePort}' | tr ' ' '\n')"
```

