# 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 17.0.1  \
--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')"
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/kubernetes/helm/helm-an-zhuang-mongodb-fu-ben-ji-qun.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
