> ## Documentation Index
> Fetch the complete documentation index at: https://ayakaleaf-pro.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 3. 部署 MongoDB 與 Redis

> 以複本集執行 MongoDB，並以持久化方式執行 Redis，或指向您自己的服務。

Ayakaleaf Pro 需要：

* 以**複本集**執行的 **MongoDB 8**（它會使用交易）。分散在三個節點上的三個成員可以承受失去一個節點；只有一個成員也能運作。
* **Redis 7**，一台啟用 AOF 持久化的伺服器。Redis 保存尚未寫入 MongoDB 的編輯、工作階段，以及 Overleaf 各服務之間的訊息。Overleaf 只會連線至單一 Redis 伺服器：不支援 Sentinel 與 Redis Cluster。

> [!NOTE]
>
> 您也可以改用代管服務，例如 MongoDB Atlas 或您雲端平台的 Redis。請略過本頁，並在[步驟 4](https://ayakaleaf-pro.mintlify.site/zh-TW/on-premises/installation/using-kubernetes/4.-personalizing-your-instance.md) 中將 `OVERLEAF_MONGO_URL` 與 `OVERLEAF_REDIS_HOST` 設為這些服務。

**1. MongoDB**

```yaml title="10-mongo.yaml" wrap theme={null}
apiVersion: v1
kind: Service
metadata:
  name: mongo
  namespace: overleaf
spec:
  clusterIP: None                 # headless: gives mongo-0.mongo, mongo-1.mongo, ...
  publishNotReadyAddresses: true  # members must resolve each other before the set is initiated
  selector:
    app: mongo
  ports:
    - name: mongo
      port: 27017
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongo
  namespace: overleaf
spec:
  serviceName: mongo
  replicas: 3
  selector:
    matchLabels:
      app: mongo
  template:
    metadata:
      labels:
        app: mongo
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchLabels:
                  app: mongo
              topologyKey: kubernetes.io/hostname
      containers:
        - name: mongo
          image: mongo:8.0
          args:
            - --replSet=overleaf
            - --bind_ip_all
            - --wiredTigerCacheSizeGB=0.25   # default is 50% of (RAM - 1 GB); size it for your nodes
          # env:
          #   - name: GLIBC_TUNABLES        # only on kernel 6.19+ (SERVER-121912)
          #     value: glibc.pthread.rseq=1
          ports:
            - containerPort: 27017
          readinessProbe:
            tcpSocket:
              port: 27017
          resources:
            requests:
              cpu: 100m
              memory: 384Mi
            limits:
              memory: 768Mi
          volumeMounts:
            - name: data
              mountPath: /data/db
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        resources:
          requests:
            storage: 5Gi
---
# Initiates the replica set once. Safe to re-run: it does nothing when the set exists.
apiVersion: batch/v1
kind: Job
metadata:
  name: mongo-init-replica-set
  namespace: overleaf
spec:
  backoffLimit: 20
  template:
    spec:
      restartPolicy: OnFailure
      containers:
        - name: init
          image: mongo:8.0
          command:
            - mongosh
            - --quiet
            - --host=mongo-0.mongo
            - --eval
            - |
              try {
                rs.status()
                print('replica set already initiated')
              } catch (e) {
                rs.initiate({
                  _id: 'overleaf',
                  members: [
                    { _id: 0, host: 'mongo-0.mongo.overleaf.svc.cluster.local:27017' },
                    { _id: 1, host: 'mongo-1.mongo.overleaf.svc.cluster.local:27017' },
                    { _id: 2, host: 'mongo-2.mongo.overleaf.svc.cluster.local:27017' },
                  ],
                })
              }
```

```bash theme={null}
kubectl apply -f 10-mongo.yaml
kubectl -n overleaf rollout status statefulset/mongo
kubectl -n overleaf wait --for=condition=complete job/mongo-init-replica-set --timeout=5m
kubectl -n overleaf exec mongo-0 -- mongosh --quiet --eval 'rs.status().members.map(m => m.name + " " + m.stateStr)'
```

幾秒後，應該會有一個成員為 `PRIMARY`，其餘為 `SECONDARY`。Job 會持續重試直到所有成員都回應，因此出現幾個失敗的 Job Pod 是正常的。

* Headless Service 需要 `publishNotReadyAddresses: true`：成員必須在複本集建立之前就能以名稱找到彼此。
* 成員是以其穩定的名稱（`mongo-0.mongo.overleaf.svc.cluster.local`）加入，絕不使用每次重新啟動都會改變的 Pod IP。
* 若只要一個成員，請設定 `replicas: 1`，並在 Job 中只保留 `mongo-0`。

**2. Redis**

```yaml title="20-redis.yaml" wrap theme={null}
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: overleaf
spec:
  selector:
    app: redis
  ports:
    - name: redis
      port: 6379
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
  namespace: overleaf
spec:
  serviceName: redis
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
        - name: redis
          image: redis:7.4
          args: [--appendonly, "yes"]
          ports:
            - containerPort: 6379
          readinessProbe:
            tcpSocket:
              port: 6379
          resources:
            requests:
              cpu: 50m
              memory: 128Mi
            limits:
              memory: 512Mi
          volumeMounts:
            - name: data
              mountPath: /data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        resources:
          requests:
            storage: 2Gi
```

```bash theme={null}
kubectl apply -f 20-redis.yaml
kubectl -n overleaf rollout status statefulset/redis
```

### Q\&A

> [accordion] MongoDB 8 在較新的核心上啟動時當機，為什麼？
>
> \*\*回答：\*\*MongoDB 8 在 Linux 核心 6.19 及更新版本上會失敗（[SERVER-121912](https://jira.mongodb.org/browse/SERVER-121912)）。請取消 `10-mongo.yaml` 中 `GLIBC_TUNABLES` 環境變數的註解。

> [accordion] MongoDB 需要多少記憶體？
>
> \*\*回答：\*\*預設情況下，MongoDB 會使用節點記憶體的一半減去 1 GB 作為快取，而且它看到的是節點的記憶體，而非 Pod 的限制。請依您的節點設定 `--wiredTigerCacheSizeGB`；在我們 4 GB 的測試節點上，`0.25` 讓每個成員維持在約 200 至 260 MiB。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.