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

     1  ---
     2  title: Create and connect to a MySQL Cluster
     3  description: How to create and connect to a MySQL cluster
     4  keywords: [mysql, create a mysql cluster, connect to a mysql 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 MySQL cluster
    13  
    14  This tutorial shows how to create and connect to a MySQL cluster.
    15  
    16  ## Create a MySQL 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 MySQL cluster by kbcli.
    21  * [Install KubeBlocks by kbcli](./../../installation/install-with-kbcli/install-kubeblocks-with-kbcli.md) or [install KubeBlocks by Helm](./../../installation/install-with-helm/install-kubeblocks-with-helm.md).
    22  * Make sure the ApeCloud MySQL 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    apecloud-mysql                 Helm   Enabled                   true
    34    ...
    35    ```
    36  
    37    </TabItem>
    38  
    39    <TabItem value="kubectl" label="kubectl">
    40  
    41    ```bash
    42    kubectl get addons.extensions.kubeblocks.io apecloud-mysql
    43    >
    44    NAME             TYPE   STATUS    AGE
    45    apecloud-mysql   Helm   Enabled   61s
    46    ```
    47  
    48    </TabItem>
    49    </Tabs>
    50  
    51  * View all the database types and versions available for creating a cluster.
    52  
    53    <Tabs>
    54  
    55    <TabItem value="kbcli" label="kbcli" default>
    56  
    57    ```bash
    58    kbcli clusterdefinition list
    59  
    60    kbcli clusterversion list
    61    ```
    62  
    63    </TabItem>
    64  
    65    <TabItem value="kubectl" label="kubectl">
    66    
    67    Make sure the `apecloud-mysql` cluster definition is installed with `kubectl get clusterdefinition apecloud-mysql`.
    68  
    69    ```bash
    70    kubectl get clusterdefinition apecloud-mysql
    71    >
    72    NAME             MAIN-COMPONENT-NAME   STATUS      AGE
    73    apecloud-mysql   mysql                 Available   85m
    74    ```
    75  
    76    View all available versions for creating a cluster.
    77  
    78    ```bash
    79    kubectl get clusterversions -l clusterdefinition.kubeblocks.io/name=apecloud-mysql
    80    ```
    81  
    82    </TabItem>
    83  
    84    </Tabs>
    85  
    86  * To keep things isolated, create a separate namespace called `demo` throughout this tutorial.
    87  
    88    ```bash
    89    kubectl create namespace demo
    90    ```
    91  
    92  ### Create a cluster
    93  
    94  KubeBlocks supports creating two types of MySQL clusters: Standalone and RaftGroup Cluster. 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 RaftGroup Cluster, which creates a cluster with three replicas. And to ensure high availability, all replicas are distributed on different nodes by default.
    95  
    96  <Tabs>
    97  
    98  <TabItem value="kbcli" label="kbcli" default>
    99  
   100  Create a Standalone.
   101  
   102  ```bash
   103  kbcli cluster create mysql <clustername>
   104  ```
   105  
   106  Create a RaftGroup Cluster.
   107  
   108  ```bash
   109  kbcli cluster create mysql --mode raftGroup <clustername>
   110  ```
   111  
   112  If you only have one node for deploying a RaftGroup Cluster, set the `availability-policy` as `none` when creating a RaftGroup Cluster.
   113  
   114  ```bash
   115  kbcli cluster create mysql --mode raftGroup --availability-policy none <clustername>
   116  ```
   117  
   118  :::note
   119  
   120  * In the production environment, it is not recommended to deploy all replicas on one node, which may decrease the cluster availability.
   121  * Run the command below to view the flags for creating a MySQL cluster and the default values.
   122    
   123    ```bash
   124    kbcli cluster create mysql -h
   125    ```
   126  
   127  :::
   128  
   129  </TabItem>
   130  
   131  <TabItem value="kubectl" label="kubectl">
   132  
   133  KubeBlocks implements a `Cluster` CRD to define a cluster. Here is an example of creating a RaftGroup Cluster.
   134  
   135     ```bash
   136     cat <<EOF | kubectl apply -f -
   137     apiVersion: apps.kubeblocks.io/v1alpha1
   138     kind: Cluster
   139     metadata:
   140       name: mysql-cluster
   141       namespace: demo
   142     spec:
   143       clusterDefinitionRef: apecloud-mysql
   144       clusterVersionRef: ac-mysql-8.0.30
   145       componentSpecs:
   146       - componentDefRef: mysql
   147         name: mysql
   148         replicas: 3
   149         resources:
   150           limits:
   151             cpu: "1"
   152             memory: 1Gi
   153           requests:
   154             cpu: "1"
   155             memory: 1Gi
   156         volumeClaimTemplates:
   157         - name: data
   158           spec:
   159             accessModes:
   160             - ReadWriteOnce
   161             resources:
   162               requests:
   163                 storage: 20Gi
   164       terminationPolicy: Delete
   165     EOF
   166     ```
   167  
   168  * `spec.clusterDefinitionRef` is the name of the cluster definition CRD that defines the cluster components.
   169  * `spec.clusterVersionRef` is the name of the cluster version CRD that defines the cluster version.
   170  * `spec.componentSpecs` is the list of components that define the cluster components.
   171  * `spec.componentSpecs.componentDefRef` is the name of the component definition that is defined in the cluster definition and you can get the component definition names with `kubectl get clusterdefinition apecloud-mysql -o json | jq '.spec.componentDefs[].name'`.
   172  * `spec.componentSpecs.name` is the name of the component.
   173  * `spec.componentSpecs.replicas` is the number of replicas of the component.
   174  * `spec.componentSpecs.resources` is the resource requirements of the component.
   175  * `spec.componentSpecs.volumeClaimTemplates` is the list of volume claim templates that define the volume claim templates for the component.
   176  * `spec.terminationPolicy` is the policy of cluster termination. The default value is `Delete`. Valid values are `DoNotTerminate`, `Halt`, `Delete`, `WipeOut`. `DoNotTerminate` blocks deletion operation. `Halt` deletes 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 a backup storage location.
   177  
   178  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=mysql-cluster -n demo`.
   179  
   180  ```bash
   181  kubectl get all,secret,rolebinding,serviceaccount -l app.kubernetes.io/instance=mysql-cluster -n demo
   182  ```
   183  
   184  Run the following command to see the created MySQL cluster object:
   185  
   186  ```bash
   187  kubectl get cluster mysql-cluster -n demo -o yaml
   188  ```
   189  
   190  <details>
   191  <summary>Output</summary>
   192  
   193  ```yaml
   194  apiVersion: apps.kubeblocks.io/v1alpha1
   195  kind: Cluster
   196  metadata:
   197    annotations:
   198      kubectl.kubernetes.io/last-applied-configuration: |
   199        {"apiVersion":"apps.kubeblocks.io/v1alpha1","kind":"Cluster","metadata":{"annotations":{},"name":"mysql-cluster","namespace":"demo"},"spec":{"clusterDefinitionRef":"apecloud-mysql","clusterVersionRef":"ac-mysql-8.0.30","componentSpecs":[{"componentDefRef":"mysql","name":"mysql","replicas":1,"resources":{"limits":{"cpu":"0.5","memory":"1Gi"},"requests":{"cpu":"0.5","memory":"1Gi"}},"volumeClaimTemplates":[{"name":"data","spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"20Gi"}}}}]}],"terminationPolicy":"Delete"}}
   200    creationTimestamp: "2023-07-17T09:03:23Z"
   201    finalizers:
   202    - cluster.kubeblocks.io/finalizer
   203    generation: 1
   204    labels:
   205      clusterdefinition.kubeblocks.io/name: apecloud-mysql
   206      clusterversion.kubeblocks.io/name: ac-mysql-8.0.30
   207    name: mysql-cluster
   208    namespace: demo
   209    resourceVersion: "27158"
   210    uid: de7c9fa4-7b94-4227-8852-8d76263aa326
   211  spec:
   212    clusterDefinitionRef: apecloud-mysql
   213    clusterVersionRef: ac-mysql-8.0.30
   214    componentSpecs:
   215    - componentDefRef: mysql
   216      monitor: false
   217      name: mysql
   218      noCreatePDB: false
   219      replicas: 1
   220      resources:
   221        limits:
   222          cpu: "0.5"
   223          memory: 1Gi
   224        requests:
   225          cpu: "0.5"
   226          memory: 1Gi
   227      volumeClaimTemplates:
   228      - name: data
   229        spec:
   230          accessModes:
   231          - ReadWriteOnce
   232          resources:
   233            requests:
   234              storage: 20Gi
   235    terminationPolicy: Delete
   236  status:
   237    clusterDefGeneration: 2
   238    components:
   239      mysql:
   240        consensusSetStatus:
   241          leader:
   242            accessMode: None
   243            name: ""
   244            pod: Unknown
   245        phase: Failed
   246        podsReady: true
   247        podsReadyTime: "2023-07-17T09:03:37Z"
   248    conditions:
   249    - lastTransitionTime: "2023-07-17T09:03:23Z"
   250      message: 'The operator has started the provisioning of Cluster: mysql-cluster'
   251      observedGeneration: 1
   252      reason: PreCheckSucceed
   253      status: "True"
   254      type: ProvisioningStarted
   255    - lastTransitionTime: "2023-07-17T09:03:23Z"
   256      message: Successfully applied for resources
   257      observedGeneration: 1
   258      reason: ApplyResourcesSucceed
   259      status: "True"
   260      type: ApplyResources
   261    - lastTransitionTime: "2023-07-17T09:03:37Z"
   262      message: all pods of components are ready, waiting for the probe detection successful
   263      reason: AllReplicasReady
   264      status: "True"
   265      type: ReplicasReady
   266    - lastTransitionTime: "2023-07-17T09:03:23Z"
   267      message: 'pods are unavailable in Components: [mysql], refer to related component
   268        message in Cluster.status.components'
   269      reason: ComponentsNotReady
   270      status: "False"
   271      type: Ready
   272    observedGeneration: 1
   273    phase: Running
   274  ```
   275  
   276  </details>
   277  
   278  </TabItem>
   279  
   280  </Tabs>
   281  
   282  ## Connect to a MySQL Cluster
   283  
   284  <Tabs>
   285  
   286  <TabItem value="kbcli" label="kbcli" default>
   287  
   288  ```bash
   289  kbcli cluster connect <clustername>  --namespace <name>
   290  ```
   291  
   292  </TabItem>
   293  
   294  <TabItem value="kubectl" label="kubectl">
   295  
   296  You can use `kubectl exec` to exec into a Pod and connect to a database.
   297  
   298  KubeBlocks operator creates a new Secret called `mysql-cluster-conn-credential` to store the connection credential of the MySQL cluster. This secret contains the following keys:
   299  
   300  * `username`: the root username of the MySQL cluster.
   301  * `password`: the password of the root user.
   302  * `port`: the port of the MySQL cluster.
   303  * `host`: the host of the MySQL cluster.
   304  * `endpoint`: the endpoint of the MySQL cluster and it is the same as `host:port`.
   305  
   306  1. Run the command below to get the `username` and `password` for the `kubectl exec` command.
   307  
   308     ```bash
   309     kubectl get secrets -n demo mysql-cluster-conn-credential -o jsonpath='{.data.\username}' | base64 -d
   310     >
   311     root
   312  
   313     kubectl get secrets -n demo mysql-cluster-conn-credential -o jsonpath='{.data.\password}' | base64 -d
   314     >
   315     2gvztbvz
   316     ```
   317  
   318  2. Exec into the Pod `mysql-cluster-mysql-0` and connect to the database using username and password.
   319  
   320     ```bash
   321     kubectl exec -ti -n demo mysql-cluster-mysql-0 -- bash
   322  
   323     mysql -uroot -p2gvztbvz
   324     ```
   325  
   326  </TabItem>
   327  
   328  <TabItem value="port-forward" label="port-forward">
   329  
   330  You can also port forward the service to connect to a database from your local machine.
   331  
   332  1. Run the following command to port forward the service.
   333  
   334     ```bash
   335     kubectl port-forward svc/mysql-cluster-mysql 3306:3306 -n demo
   336     ```
   337  
   338  2. Open a new terminal and run the following command to connect to the database.
   339  
   340     ```bash
   341     mysql -uroot -p2gvztbvz
   342     ```
   343  
   344  </TabItem>
   345  
   346  </Tabs>
   347  
   348  For the detailed database connection guide, refer to [Connect database](./../../connect_database/overview-of-database-connection.md).