On top of CockroachDB's built-in automation, you can use a third-party orchestration system to simplify and automate even more of your operations, from deployment to scaling to overall cluster management.
This page walks you through a simple demonstration, using the open-source Kubernetes orchestration system. Using either the CockroachDB Helm chart or a few configuration files, you'll quickly create a 3-node local cluster. You'll run some SQL commands against the cluster and then simulate node failure, watching how Kubernetes auto-restarts without the need for any manual intervention. You'll then scale the cluster with a single command before shutting the cluster down, again with a single command.
To orchestrate a physically distributed cluster in production, see Orchestrated Deployments.
Before you begin
Before getting started, it's helpful to review some Kubernetes-specific terminology:
| Feature | Description |
|---|---|
| minikube | This is the tool you'll use to run a Kubernetes cluster inside a VM on your local workstation. |
| pod | A pod is a group of one of more Docker containers. In this tutorial, all pods will run on your local workstation, each containing one Docker container running a single CockroachDB node. You'll start with 3 pods and grow to 4. |
| StatefulSet | A StatefulSet is a group of pods treated as stateful units, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart. StatefulSets are considered stable as of Kubernetes version 1.9 after reaching beta in version 1.5. |
| persistent volume | A persistent volume is a piece of storage mounted into a pod. The lifetime of a persistent volume is decoupled from the lifetime of the pod that's using it, ensuring that each CockroachDB node binds back to the same storage on restart. When using minikube, persistent volumes are external temporary directories that endure until they are manually deleted or until the entire Kubernetes cluster is deleted. |
| persistent volume claim | When pods are created (one per CockroachDB node), each pod will request a persistent volume claim to “claim” durable storage for its node. |
Step 1. Start Kubernetes
Follow Kubernetes' documentation to install
minikube, the tool used to run Kubernetes locally, for your OS. This includes installing a hypervisor andkubectl, the command-line tool used to manage Kubernetes from your local workstation.Note:Make sure you installminikubeversion 0.21.0 or later. Earlier versions do not include a Kubernetes server that supports themaxUnavailabilityfield andPodDisruptionBudgetresource type used in the CockroachDB StatefulSet configuration.Start a local Kubernetes cluster:
$ minikube start
Step 2. Start CockroachDB
To start your CockroachDB cluster, you can either use our StatefulSet configuration and related files directly, or you can use the Helm package manager for Kubernetes to simplify the process.
From your local workstation, use our
cockroachdb-statefulset.yamlfile to create the StatefulSet that automatically creates 3 pods, each with a CockroachDB node running inside it.Download
cockroachdb-statefulset.yaml:$ curl -O https://raw.githubusercontent.com/cockroachdb/cockroach/master/cloud/kubernetes/cockroachdb-statefulset.yamlWarning:To avoid running out of memory when CockroachDB is not the only pod on a Kubernetes node, you must set memory limits explicitly. This is because CockroachDB does not detect the amount of memory allocated to its pod when run in Kubernetes. Specify this amount by adjusting
resources.requests.memoryandresources.limits.memoryincockroachdb-statefulset.yaml. Their values should be identical.We recommend setting
cacheandmax-sql-memoryeach to 1/4 of your memory allocation. For example, if you are allocating 8Gi of memory to each CockroachDB node, substitute the following values in this line:--cache 2Gi --max-sql-memory 2GiUse the file to create the StatefulSet and start the cluster:
$ kubectl create -f cockroachdb-statefulset.yamlservice/cockroachdb-public created service/cockroachdb created poddisruptionbudget.policy/cockroachdb-budget created statefulset.apps/cockroachdb createdAlternatively, if you'd rather start with a configuration file that has been customized for performance:
Download our performance version of
cockroachdb-statefulset-insecure.yaml:$ curl -O https://raw.githubusercontent.com/cockroachdb/cockroach/master/cloud/kubernetes/performance/cockroachdb-statefulset-insecure.yamlModify the file wherever there is a
TODOcomment.Use the file to create the StatefulSet and start the cluster:
$ kubectl create -f cockroachdb-statefulset-insecure.yaml
Confirm that three pods are
Runningsuccessfully. Note that they will not be consideredReadyuntil after the cluster has been initialized:$ kubectl get podsNAME READY STATUS RESTARTS AGE cockroachdb-0 0/1 Running 0 2m cockroachdb-1 0/1 Running 0 2m cockroachdb-2 0/1 Running 0 2mConfirm that the persistent volumes and corresponding claims were created successfully for all three pods:
$ kubectl get persistentvolumesNAME CAPACITY ACCESSMODES RECLAIMPOLICY STATUS CLAIM REASON AGE pvc-52f51ecf-8bd5-11e6-a4f4-42010a800002 1Gi RWO Delete Bound default/datadir-cockroachdb-0 26s pvc-52fd3a39-8bd5-11e6-a4f4-42010a800002 1Gi RWO Delete Bound default/datadir-cockroachdb-1 27s pvc-5315efda-8bd5-11e6-a4f4-42010a800002 1Gi RWO Delete Bound default/datadir-cockroachdb-2 27sUse our
cluster-init.yamlfile to perform a one-time initialization that joins the CockroachDB nodes into a single cluster:$ kubectl create \ -f https://raw.githubusercontent.com/cockroachdb/cockroach/master/cloud/kubernetes/cluster-init.yamljob.batch/cluster-init createdConfirm that cluster initialization has completed successfully. The job should be considered successful and the Kubernetes pods should soon be considered
Ready:$ kubectl get job cluster-initNAME COMPLETIONS DURATION AGE cluster-init 1/1 7s 27s$ kubectl get podsNAME READY STATUS RESTARTS AGE cluster-init-cqf8l 0/1 Completed 0 56s cockroachdb-0 1/1 Running 0 7m51s cockroachdb-1 1/1 Running 0 7m51s cockroachdb-2 1/1 Running 0 7m51s
The StatefulSet configuration sets all CockroachDB nodes to log to stderr, so if you ever need access to a pod/node's logs to troubleshoot, use kubectl logs <podname> rather than checking the log on the persistent volume.
Install the Helm server, known as Tiller.
In the likely case that your Kubernetes cluster uses RBAC (e.g., if you are using GKE), you first need to create RBAC resources to grant Tiller access to the Kubernetes API:
Create a
rbac-config.yamlfile to define a role and service account:apiVersion: v1 kind: ServiceAccount metadata: name: tiller namespace: kube-system --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: tiller roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: tiller namespace: kube-systemCreate the service account:
$ kubectl create -f rbac-config.yamlserviceaccount/tiller created clusterrolebinding.rbac.authorization.k8s.io/tiller createdStart the Helm server and install Tiller:
Note:Tiller does not currently support Kubernetes 1.16.0. The following command includes a workaround to install Tiller for use with 1.16.0.
$ helm init --service-account tiller --override spec.selector.matchLabels.'name'='tiller',spec.selector.matchLabels.'app'='helm' --output yaml | sed 's@apiVersion: extensions/v1beta1@apiVersion: apps/v1@' | kubectl apply -f -
Update your Helm chart repositories to ensure that you're using the latest CockroachDB chart:
$ helm repo updateInstall the CockroachDB Helm chart, providing a "release" name to identify and track this particular deployment of the chart:
Note:This tutorial uses
my-releaseas the release name. If you use a different value, be sure to adjust the release name in subsequent commands.$ helm install --name my-release --set Resources.requests.memory="<your memory allocation>",CacheSize="<your cache size>",MaxSQLMemory="<your SQL memory size>" cockroachdb/cockroachdbBehind the scenes, this command uses our
cockroachdb-statefulset.yamlfile to create the StatefulSet that automatically creates 3 pods, each with a CockroachDB node running inside it, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart.Warning:To avoid running out of memory when CockroachDB is not the only pod on a Kubernetes node, you must set memory limits explicitly. This is because CockroachDB does not detect the amount of memory allocated to its pod when run in Kubernetes.
We recommend setting
CacheSizeandMaxSQLMemoryeach to 1/4 of the memory allocation specified in yourResources.requests.memoryparameter. For example, if you are allocating 8GiB of memory to each CockroachDB node, use the following values with the--setflag in thehelm installcommand:Requests.resources.memory="8GiB",CacheSize="2GiB",MaxSQLMemory="2GiB"Note:You can customize your deployment by passing configuration parameters to
helm installusing the--set key=value[,key=value]flag. For a production cluster, you should consider modifying theStorageandStorageClassparameters. This chart defaults to 100 GiB of disk space per pod, but you may want more or less depending on your use case, and the default persistent volumeStorageClassin your environment may not be what you want for a database (e.g., on GCE and Azure the default is not SSD).Confirm that three pods are
Runningsuccessfully and that the one-time cluster initialization hasCompleted:$ kubectl get podsNAME READY STATUS RESTARTS AGE my-release-cockroachdb-0 1/1 Running 0 1m my-release-cockroachdb-1 1/1 Running 0 1m my-release-cockroachdb-2 1/1 Running 0 1m my-release-cockroachdb-init-k6jcr 0/1 Completed 0 1mConfirm that the persistent volumes and corresponding claims were created successfully for all three pods:
$ kubectl get persistentvolumesNAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-64878ebf-f3f0-11e8-ab5b-42010a8e0035 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-0 standard 51s pvc-64945b4f-f3f0-11e8-ab5b-42010a8e0035 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-1 standard 51s pvc-649d920d-f3f0-11e8-ab5b-42010a8e0035 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-2 standard 51s
The StatefulSet configuration sets all CockroachDB nodes to log to stderr, so if you ever need access to a pod/node's logs to troubleshoot, use kubectl logs <podname> rather than checking the log on the persistent volume.
Step 3. Use the built-in SQL client
Launch a temporary interactive pod and start the built-in SQL client inside it:
$ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach:v19.1.11 \ --rm \ --restart=Never \ -- sql \ --insecure \ --host=cockroachdb-public$ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach:v19.1.11 \ --rm \ --restart=Never \ -- sql \ --insecure \ --host=my-release-cockroachdb-publicRun some basic CockroachDB SQL statements:
> CREATE DATABASE bank;> CREATE TABLE bank.accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), balance DECIMAL );> INSERT INTO bank.accounts (balance) VALUES (1000.50), (20000), (380), (500), (55000);> SELECT * FROM bank.accounts;id | balance +--------------------------------------+---------+ 6f123370-c48c-41ff-b384-2c185590af2b | 380 990c9148-1ea0-4861-9da7-fd0e65b0a7da | 1000.50 ac31c671-40bf-4a7b-8bee-452cff8a4026 | 500 d58afd93-5be9-42ba-b2e2-dc00dcedf409 | 20000 e6d8f696-87f5-4d3c-a377-8e152fdc27f7 | 55000 (5 rows)Exit the SQL shell and delete the temporary pod:
> \q
Step 4. Access the Admin UI
To access the cluster's Admin UI:
In a new terminal window, port-forward from your local machine to one of the pods:
$ kubectl port-forward cockroachdb-0 8080$ kubectl port-forward my-release-cockroachdb-0 8080Forwarding from 127.0.0.1:8080 -> 8080Note:Theport-forwardcommand must be run on the same machine as the web browser in which you want to view the Admin UI. If you have been running these commands from a cloud instance or other non-local shell, you will not be able to view the UI without configuringkubectllocally and running the aboveport-forwardcommand on your local machine.Go to http://localhost:8080.
In the UI, verify that the cluster is running as expected:
- Click View nodes list on the right to ensure that all nodes successfully joined the cluster.
- Click the Databases tab on the left to verify that
bankis listed.
Step 5. Simulate node failure
Based on the replicas: 3 line in the StatefulSet configuration, Kubernetes ensures that three pods/nodes are running at all times. When a pod/node fails, Kubernetes automatically creates another pod/node with the same network identity and persistent storage.
To see this in action:
Terminate one of the CockroachDB nodes:
$ kubectl delete pod cockroachdb-2pod "cockroachdb-2" deleted$ kubectl delete pod my-release-cockroachdb-2pod "my-release-cockroachdb-2" deletedIn the Admin UI, the Cluster Overview will soon show one node as Suspect. As Kubernetes auto-restarts the node, watch how the node once again becomes healthy.
Back in the terminal, verify that the pod was automatically restarted:
$ kubectl get pod cockroachdb-2NAME READY STATUS RESTARTS AGE cockroachdb-2 1/1 Running 0 12s$ kubectl get pod my-release-cockroachdb-2NAME READY STATUS RESTARTS AGE my-release-cockroachdb-2 1/1 Running 0 44s
Step 6. Add nodes
Use the
kubectl scalecommand to add a pod for another CockroachDB node:$ kubectl scale statefulset cockroachdb --replicas=4statefulset "cockroachdb" scaled$ kubectl scale statefulset my-release-cockroachdb --replicas=4statefulset "my-release-cockroachdb" scaledVerify that the pod for a fourth node,
cockroachdb-3, was added successfully:$ kubectl get podsNAME READY STATUS RESTARTS AGE cockroachdb-0 1/1 Running 0 28m cockroachdb-1 1/1 Running 0 27m cockroachdb-2 1/1 Running 0 10m cockroachdb-3 1/1 Running 0 5s example-545f866f5-2gsrs 1/1 Running 0 25mNAME READY STATUS RESTARTS AGE my-release-cockroachdb-0 1/1 Running 0 28m my-release-cockroachdb-1 1/1 Running 0 27m my-release-cockroachdb-2 1/1 Running 0 10m my-release-cockroachdb-3 1/1 Running 0 5s example-545f866f5-2gsrs 1/1 Running 0 25m
Step 7. Remove nodes
To safely remove a node from your cluster, you must first decommission the node and only then adjust the Replicas value of your StatefulSet configuration to permanently remove it. This sequence is important because the decommissioning process lets a node finish in-flight requests, rejects any new requests, and transfers all range replicas and range leases off the node.
If you remove nodes without first telling CockroachDB to decommission them, you may cause data or even cluster unavailability. For more details about how this works and what to consider before removing nodes, see Decommission Nodes.
Launch a temporary interactive pod and use the
cockroach node statuscommand to get the internal IDs of nodes:$ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach:v19.1.11 \ --rm \ --restart=Never \ -- node status \ --insecure \ --host=cockroachdb-publicid | address | build | started_at | updated_at | is_available | is_live +----+---------------------------------------------------------------------------------+--------+----------------------------------+----------------------------------+--------------+---------+ 1 | cockroachdb-0.cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 16:04:36.486082+00:00 | 2018-11-29 18:24:24.587454+00:00 | true | true 2 | cockroachdb-2.cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 16:55:03.880406+00:00 | 2018-11-29 18:24:23.469302+00:00 | true | true 3 | cockroachdb-1.cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 16:04:41.383588+00:00 | 2018-11-29 18:24:25.030175+00:00 | true | true 4 | cockroachdb-3.cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 17:31:19.990784+00:00 | 2018-11-29 18:24:26.041686+00:00 | true | true (4 rows)$ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach:v19.1.11 \ --rm \ --restart=Never \ -- node status \ --insecure \ --host=my-release-cockroachdb-publicid | address | build | started_at | updated_at | is_available | is_live +----+---------------------------------------------------------------------------------+--------+----------------------------------+----------------------------------+--------------+---------+ 1 | my-release-cockroachdb-0.my-release-cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 16:04:36.486082+00:00 | 2018-11-29 18:24:24.587454+00:00 | true | true 2 | my-release-cockroachdb-2.my-release-cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 16:55:03.880406+00:00 | 2018-11-29 18:24:23.469302+00:00 | true | true 3 | my-release-cockroachdb-1.my-release-cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 16:04:41.383588+00:00 | 2018-11-29 18:24:25.030175+00:00 | true | true 4 | my-release-cockroachdb-3.my-release-cockroachdb.default.svc.cluster.local:26257 | v19.1.11 | 2018-11-29 17:31:19.990784+00:00 | 2018-11-29 18:24:26.041686+00:00 | true | true (4 rows)Note the ID of the node with the highest number in its address (in this case, the address including
cockroachdb-3) and use thecockroach node decommissioncommand to decommission it:Note:It's important to decommission the node with the highest number in its address because, when you reduce the replica count, Kubernetes will remove the pod for that node.
$ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach:v19.1.11 \ --rm \ --restart=Never \ -- node decommission <node ID> \ --insecure \ --host=cockroachdb-public$ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach:v19.1.11 \ --rm \ --restart=Never \ -- node decommission <node ID> \ --insecure \ --host=my-release-cockroachdb-publicYou'll then see the decommissioning status print to
stderras it changes:id | is_live | replicas | is_decommissioning | is_draining +---+---------+----------+--------------------+-------------+ 4 | true | 73 | true | false (1 row)Once the node has been fully decommissioned and stopped, you'll see a confirmation:
id | is_live | replicas | is_decommissioning | is_draining +---+---------+----------+--------------------+-------------+ 4 | true | 0 | true | false (1 row) No more data reported on target nodes. Please verify cluster health before removing the nodes.Once the node has been decommissioned, remove a pod from your StatefulSet:
$ kubectl scale statefulset cockroachdb --replicas=3statefulset "cockroachdb" scaled$ helm upgrade \ my-release \ cockroachdb/cockroachdb \ --set Replicas=3 \ --reuse-values
Step 8. Stop the cluster
If you plan to restart the cluster, use the
minikube stopcommand. This shuts down the minikube virtual machine but preserves all the resources you created:$ minikube stopStopping local Kubernetes cluster... Machine stopped.You can restore the cluster to its previous state with
minikube start.If you do not plan to restart the cluster, use the
minikube deletecommand. This shuts down and deletes the minikube virtual machine and all the resources you created, including persistent volumes:$ minikube deleteDeleting local Kubernetes cluster... Machine deleted.Tip:To retain logs, copy them from each pod'sstderrbefore deleting the cluster and all its resources. To access a pod's standard error stream, runkubectl logs <podname>.
See also
Explore other core CockroachDB benefits and features:
- Data Replication
- Fault Tolerance & Recovery
- Automatic Rebalancing
- Serializable Transactions
- Cross-Cloud Migration
- Follow-the-Workload
- Orchestration
- JSON Support
You might also want to learn how to orchestrate a production deployment of CockroachDB with Kubernetes.