github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/docs/user_docs/kubeblocks-for-mongodb/cluster-management/create-and-connect-to-a-mongodb-cluster.md (about)

     1  ---
     2  title: Create and connect to a MongoDB Cluster
     3  description: How to create and connect to a MongoDB cluster
     4  keywords: [mogodb, create a mongodb cluster]
     5  sidebar_position: 1
     6  sidebar_label: Create and connect
     7  ---
     8  
     9  import Tabs from '@theme/Tabs';
    10  import TabItem from '@theme/TabItem';
    11  
    12  # Create and connect to a MongoDB cluster
    13  
    14  This tutorial shows how to create and connect to a MongoDB cluster.
    15  
    16  ## Create a MongoDB cluster
    17  
    18  ### Before you start
    19  
    20  * [Install kbcli](./../../installation/install-with-kbcli/install-kbcli.md) if you want to create and connect a cluster by kbcli.
    21  * Install KubeBlocks: You can install KubeBlocks by [kbcli](./../../installation/install-with-kbcli/install-kubeblocks-with-kbcli.md) or by [Helm](./../../installation/install-with-helm/install-kubeblocks-with-helm.md).
    22  * Make sure the MongoDB add-on is enabled.
    23    
    24    <Tabs>
    25  
    26    <TabItem value="kbcli" label="kbcli" default>
    27  
    28    ```bash
    29    kbcli addon list
    30    >
    31    NAME                           TYPE   STATUS     EXTRAS         AUTO-INSTALL   INSTALLABLE-SELECTOR
    32    ...
    33    mongodb                        Helm   Enabled                   true
    34    ...
    35    ```
    36  
    37    </TabItem>
    38  
    39    <TabItem value="kubectl" label="kubectl">
    40  
    41    ```bash
    42    kubectl get clusterdefinitions mongodb
    43    >
    44    NAME      MAIN-COMPONENT-NAME   STATUS      AGE
    45    mongodb   mongodb               Available   118m
    46    ```
    47  
    48    </TabItem>
    49  
    50    </Tabs>
    51  
    52  * View all the database types and versions available for creating a cluster.
    53  
    54    <Tabs>
    55  
    56    <TabItem value="kbcli" label="kbcli" default>
    57  
    58    ```bash
    59    kbcli clusterdefinition list
    60  
    61    kbcli clusterversion list
    62    ```
    63  
    64    </TabItem>
    65  
    66    <TabItem value="kubectl" label="kubectl">
    67  
    68    Make sure the `mongodb` cluster definition is installed with `kubectl get clusterdefinitions mongodb`.
    69  
    70    ```bash
    71    kubectl get clusterdefinitions mongodb
    72    >
    73    NAME      MAIN-COMPONENT-NAME   STATUS      AGE
    74    mongodb   mongodb               Available   118m
    75    ```
    76  
    77    View all available versions for creating a cluster.
    78  
    79    ```bash
    80    kubectl get clusterversions -l clusterdefinition.kubeblocks.io/name=mongodb
    81    >
    82    NAME             CLUSTER-DEFINITION   STATUS      AGE
    83    mongodb-5.0   mongodb              Available   118m
    84    ```
    85  
    86    </TabItem>
    87  
    88    </Tabs>
    89  
    90  * To keep things isolated, create a separate namespace called `demo` throughout this tutorial.
    91  
    92    ```bash
    93    kubectl create namespace demo
    94    >
    95    namespace/demo created
    96    ```
    97  
    98  ### Create a cluster
    99  
   100  KubeBlocks supports creating two types of MongoDB clusters: Standalone and ReplicaSet. Standalone only supports one replica and can be used in scenarios with lower requirements for availability. For scenarios with high availability requirements, it is recommended to create a ReplicaSet, which creates a cluster with a three replicas to support automatic failover. And to ensure high availability, all replicas are distributed on different nodes by default.
   101  
   102  <Tabs>
   103  
   104  <TabItem value="kbcli" label="kbcli" default>
   105  
   106  Create a Standalone.
   107  
   108  ```bash
   109  kbcli cluster create mongodb <clustername>
   110  ```
   111  
   112  Create a ReplicatSet.
   113  
   114  ```bash
   115  kbcli cluster create mongodb --mode replicaset <clustername>
   116  ```
   117  
   118  If you only have one node for deploying a ReplicaSet, set the `availability-policy` as `none` when creating a ReplicaSet.
   119  
   120  ```bash
   121  kbcli cluster create mongodb --mode replicaset --availability-policy none <clustername>
   122  ```
   123  
   124  :::note
   125  
   126  * In the production environment, it is not recommended to deploy all replicas on one node, which may decrease cluster availability.
   127  * Run the command below to view the flags for creating a MongoDB cluster and the default values.
   128    
   129    ```bash
   130    kbcli cluster create mongodb -h
   131    ```
   132  
   133  :::
   134  
   135  </TabItem>
   136  
   137  <TabItem value="kubectl" label="kubectl">
   138  
   139  KubeBlocks implements a `Cluster` CRD to define a cluster. Here is an example of creating a MongoDB Standalone.
   140  
   141    ```bash
   142    cat <<EOF | kubectl apply -f -
   143    apiVersion: apps.kubeblocks.io/v1alpha1
   144    kind: Cluster
   145    metadata:
   146      name: mongodb-cluster
   147      namespace: demo
   148      labels: 
   149        helm.sh/chart: mongodb-cluster-0.6.0-alpha.36
   150        app.kubernetes.io/version: "5.0"
   151        app.kubernetes.io/instance: mongodb
   152    spec:
   153      clusterVersionRef: mongodb-5.0
   154      terminationPolicy: Delete  
   155      affinity:
   156        podAntiAffinity: Preferred
   157        topologyKeys:
   158          - kubernetes.io/hostname
   159        tenancy: SharedNode
   160      clusterDefinitionRef: mongodb
   161      componentSpecs:
   162        - name: mongodb
   163          componentDefRef: mongodb      
   164          monitor: false      
   165          replicas: 1
   166          serviceAccountName: kb-mongodb      
   167          resources:
   168            limits:
   169              cpu: "0.5"
   170              memory: "0.5Gi"
   171            requests:
   172              cpu: "0.5"
   173              memory: "0.5Gi"      
   174          volumeClaimTemplates:
   175            - name: data # ref clusterDefinition components.containers.volumeMounts.name
   176              spec:
   177                accessModes:
   178                  - ReadWriteOnce
   179                resources:
   180                  requests:
   181                    storage: 20Gi      
   182          services:
   183    EOF
   184    ```
   185  
   186  * `spec.clusterDefinitionRef` is the name of the cluster definition CRD that defines the cluster components.
   187  * `spec.clusterVersionRef` is the name of the cluster version CRD that defines the cluster version.
   188  * `spec.componentSpecs` is the list of components that define the cluster components.
   189  * `spec.componentSpecs.componentDefRef` is the name of the component definition that is defined in the cluster definition, you can get the component definition names with `kubectl get clusterdefinition mongodb -o json | jq '.spec.componentDefs[].name'`
   190  * `spec.componentSpecs.name` is the name of the component.
   191  * `spec.componentSpecs.replicas` is the number of replicas of the component.
   192  * `spec.componentSpecs.resources` is the resource requirements of the component.
   193  * `spec.componentSpecs.volumeClaimTemplates` is the list of volume claim templates that define the volume claim templates for the component.
   194  * `spec.terminationPolicy` is the policy of the cluster termination. The default value is `Delete`. Valid values are `DoNotTerminate`, `Halt`, `Delete`, `WipeOut`. `DoNotTerminate` will block delete operation. `Halt` will delete workload resources such as statefulset and deployment workloads but keep PVCs. `Delete` is based on Halt and deletes PVCs. `WipeOut` is based on Delete and wipe out all volume snapshots and snapshot data from backup storage location.
   195  
   196  KubeBlocks operator watches for the `Cluster` CRD and creates the cluster and all dependent resources. You can get all the resources created by the cluster with `kubectl get all,secret,rolebinding,serviceaccount -l app.kubernetes.io/instance=mongodb-cluster -n demo`.
   197  
   198  ```bash
   199  kubectl get all,secret,rolebinding,serviceaccount -l app.kubernetes.io/instance=mongodb-cluster -n demo
   200  ```
   201  
   202  Run the following command to see the created MongoDB cluster object.
   203  
   204  ```bash
   205  kubectl get cluster mongodb-cluster -n demo -o yaml
   206  ```
   207  
   208  <details>
   209  
   210  <summary>Output</summary>
   211  
   212  ```yaml
   213  apiVersion: apps.kubeblocks.io/v1alpha1
   214  kind: Cluster
   215  metadata:
   216    annotations:
   217      kubectl.kubernetes.io/last-applied-configuration: |
   218        {"apiVersion":"apps.kubeblocks.io/v1alpha1","kind":"Cluster","metadata":{"annotations":{},"labels":{"app.kubernetes.io/instance":"mongodb","app.kubernetes.io/version":"5.0","helm.sh/chart":"mongodb-cluster-0.6.0-alpha.36"},"name":"mongodb-cluster","namespace":"demo"},"spec":{"affinity":{"podAntiAffinity":"Preferred","tenancy":"SharedNode","topologyKeys":["kubernetes.io/hostname"]},"clusterDefinitionRef":"mongodb","clusterVersionRef":"mongodb-5.0","componentSpecs":[{"componentDefRef":"mongodb","monitor":false,"name":"mongodb","replicas":1,"resources":{"limits":{"cpu":"0.5","memory":"0.5Gi"},"requests":{"cpu":"0.5","memory":"0.5Gi"}},"serviceAccountName":"kb-mongodb","services":null,"volumeClaimTemplates":[{"name":"data","spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"20Gi"}}}}]}],"terminationPolicy":"Delete"}}
   219    creationTimestamp: "2023-07-19T08:59:48Z"
   220    finalizers:
   221    - cluster.kubeblocks.io/finalizer
   222    generation: 1
   223    labels:
   224      app.kubernetes.io/instance: mongodb
   225      app.kubernetes.io/version: 5.0
   226      clusterdefinition.kubeblocks.io/name: mongodb
   227      clusterversion.kubeblocks.io/name: mongodb-5.0
   228      helm.sh/chart: mongodb-cluster-0.6.0-alpha.36
   229    name: mongodb-cluster
   230    namespace: demo
   231    resourceVersion: "16137"
   232    uid: 6a488eaa-29f2-417f-b248-d10d0512e14a
   233  spec:
   234    affinity:
   235      podAntiAffinity: Preferred
   236      tenancy: SharedNode
   237      topologyKeys:
   238      - kubernetes.io/hostname
   239    clusterDefinitionRef: mongodb
   240    clusterVersionRef: mongodb-5.0
   241    componentSpecs:
   242    - componentDefRef: mongodb
   243      monitor: false
   244      name: mongodb
   245      noCreatePDB: false
   246      replicas: 1
   247      resources:
   248        limits:
   249          cpu: "0.5"
   250          memory: 0.5Gi
   251        requests:
   252          cpu: "0.5"
   253          memory: 0.5Gi
   254      serviceAccountName: kb-mongodb
   255      volumeClaimTemplates:
   256      - name: data
   257        spec:
   258          accessModes:
   259          - ReadWriteOnce
   260          resources:
   261            requests:
   262              storage: 20Gi
   263    terminationPolicy: Delete
   264  status:
   265    clusterDefGeneration: 2
   266    components:
   267      mongodb:
   268        consensusSetStatus:
   269          leader:
   270            accessMode: ReadWrite
   271            name: primary
   272            pod: mongodb-cluster-mongodb-0
   273        phase: Running
   274        podsReady: true
   275        podsReadyTime: "2023-07-19T09:00:24Z"
   276    conditions:
   277    - lastTransitionTime: "2023-07-19T08:59:49Z"
   278      message: 'The operator has started the provisioning of Cluster: mongodb-cluster'
   279      observedGeneration: 1
   280      reason: PreCheckSucceed
   281      status: "True"
   282      type: ProvisioningStarted
   283    - lastTransitionTime: "2023-07-19T08:59:49Z"
   284      message: Successfully applied for resources
   285      observedGeneration: 1
   286      reason: ApplyResourcesSucceed
   287      status: "True"
   288      type: ApplyResources
   289    - lastTransitionTime: "2023-07-19T09:00:24Z"
   290      message: all pods of components are ready, waiting for the probe detection successful
   291      reason: AllReplicasReady
   292      status: "True"
   293      type: ReplicasReady
   294    - lastTransitionTime: "2023-07-19T09:00:29Z"
   295      message: 'Cluster: mongodb-cluster is ready, current phase is Running'
   296      reason: ClusterReady
   297      status: "True"
   298      type: Ready
   299    observedGeneration: 1
   300    phase: Running
   301  ```
   302  
   303  </details>
   304  
   305  </TabItem>
   306  
   307  </Tabs>
   308  
   309  ## Connect to a MongoDB Cluster
   310  
   311  <Tabs>
   312  
   313  <TabItem value="kbcli" label="kbcli" default>
   314  
   315  ```bash
   316  kbcli cluster connect <clustername>  --namespace <name>
   317  ```
   318  
   319  </TabItem>
   320  
   321  <TabItem value="kubectl" label="kubectl">
   322  
   323  You can use `kubectl exec` to exec into a Pod and connect to a database.
   324  
   325  KubeBlocks operator has created a new Secret called `mongodb-cluster-conn-credential` to store the connection credential of the MongoDB cluster. This secret contains the following keys:
   326  
   327  * `username`: the root username of the MongoDB cluster.
   328  * `password`: the password of the root user.
   329  * `port`: the port of the MongoDB cluster.
   330  * `host`: the host of the MongoDB cluster.
   331  * `endpoint`: the endpoint of the MongoDB cluster and it is the same as `host:port`.
   332  
   333  1. Get the `username` and `password` to connect to this MongoDB cluster for the `kubectl exec` command.
   334  
   335  ```bash
   336  kubectl get secrets -n demo mongodb-cluster-conn-credential -o jsonpath='{.data.\username}' | base64 -d
   337  >
   338  root
   339  
   340  kubectl get secrets -n demo mongodb-cluster-conn-credential -o jsonpath='{.data.\password}' | base64 -d
   341  >
   342  svk9xzqs
   343  ```
   344  
   345  2. Exec into the Pod `mongodb-cluster-mongodb-0` and connect to the database using username and password.
   346  
   347  ```bash
   348  kubectl exec -ti -n demo mongodb-cluster-mongodb-0 -- bash
   349  
   350  root@mongodb-cluster-mongodb-0:/# mongo --username root --password svk9xzqs --authenticationDatabase admin
   351  ```
   352  
   353  </TabItem>
   354  
   355  <TabItem value="port-forward" label="port-forward">
   356  
   357  You can also port forward the service to connect to the database from your local machine. 
   358  
   359  1. Run the following command to port forward the service.
   360  
   361     ```bash
   362     kubectl port-forward -n demo svc/mongodb-cluster-mongodb 27017:27017  
   363     ```
   364  
   365  2. Open a new terminal and run the following command to connect to the database.
   366  
   367     ```bash
   368     root@mongodb-cluster-mongodb-0:/# mongo --username root --password svk9xzqs --authenticationDatabase admin
   369     ```
   370  
   371  </TabItem>
   372  
   373  </Tabs>
   374  
   375  For the detailed database connection guide, refer to [Connect database](./../../connect_database/overview-of-database-connection.md).