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 demonstrates a basic integration with 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. To deploy a 30-day free CockroachDB Cloud cluster instead of running CockroachDB yourself, see the Quickstart.
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 installminikube
version 0.21.0 or later. Earlier versions do not include a Kubernetes server that supports themaxUnavailability
field andPodDisruptionBudget
resource type used in the CockroachDB StatefulSet configuration.Start a local Kubernetes cluster:
$ minikube start
Step 2. Start CockroachDB
Choose a way to deploy and maintain the CockroachDB cluster:
- CockroachDB Kubernetes Operator (recommended)
- Helm package manager
- Manually apply our StatefulSet configuration and related files
Install the Operator
Apply the custom resource definition (CRD) for the Operator:
$ kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.15.1/install/crds.yaml
customresourcedefinition.apiextensions.k8s.io/crdbclusters.crdb.cockroachlabs.com created
By default, the Operator is configured to install in the
cockroach-operator-system
namespace and to manage CockroachDB instances for all namespaces on the cluster.If you'd like to change either of these defaults:
Download the Operator manifest:
$ curl -0 https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.15.1/install/operator.yaml
To use a custom namespace, edit all instances of
namespace: cockroach-operator-system
with your desired namespace.To limit the namespaces that will be monitored, set the
WATCH_NAMESPACE
environment variable in theDeployment
pod spec. This can be set to a single namespace, or a comma-delimited set of namespaces. When set, only thoseCrdbCluster
resources in the supplied namespace(s) will be reconciled.Instead of using the command below, apply your local version of the Operator manifest to the cluster:
$ kubectl apply -f operator.yaml
If you want to use the default namespace settings:
$ kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.15.1/install/operator.yaml
clusterrole.rbac.authorization.k8s.io/cockroach-database-role created serviceaccount/cockroach-database-sa created clusterrolebinding.rbac.authorization.k8s.io/cockroach-database-rolebinding created role.rbac.authorization.k8s.io/cockroach-operator-role created clusterrolebinding.rbac.authorization.k8s.io/cockroach-operator-rolebinding created clusterrole.rbac.authorization.k8s.io/cockroach-operator-role created serviceaccount/cockroach-operator-sa created rolebinding.rbac.authorization.k8s.io/cockroach-operator-default created deployment.apps/cockroach-operator created
Validate that the Operator is running:
$ kubectl get pods
NAME READY STATUS RESTARTS AGE cockroach-operator-6f7b86ffc4-9ppkv 1/1 Running 0 54s
Initialize the cluster
By default, the Operator will generate and sign 1 client and 1 node certificate to secure the cluster. To authenticate using your own CA, see Operate CockroachDB on Kubernetes.
Download
example.yaml
, a custom resource that tells the Operator how to configure the Kubernetes cluster.$ curl -O https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.15.1/examples/example.yaml
Note:By default, this manifest specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload.
Apply
example.yaml
:$ kubectl apply -f example.yaml
The Operator will create a StatefulSet and initialize the nodes as a cluster.
crdbcluster.crdb.cockroachlabs.com/cockroachdb created
Check that the pods were created:
$ kubectl get pods
NAME READY STATUS RESTARTS AGE cockroach-operator-6f7b86ffc4-9t9zb 1/1 Running 0 3m22s cockroachdb-0 1/1 Running 0 2m31s cockroachdb-1 1/1 Running 0 102s cockroachdb-2 1/1 Running 0 46s
Each pod should have
READY
status soon after being created.
Configure the cluster
Download and modify our StatefulSet configuration:
$ curl -O https://raw.githubusercontent.com/cockroachdb/cockroach/master/cloud/kubernetes/bring-your-own-certs/cockroachdb-statefulset.yaml
Update
secretName
with the name of the corresponding node secret.The secret names depend on your method for generating secrets. For example, if you follow the below steps using
cockroach cert
, use this secret name:secret: secretName: cockroachdb.node
By default, this manifest specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload. For details on configuring your deployment, see Operate CockroachDB on Kubernetes.
Create certificates
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.
The below steps use cockroach cert
commands to quickly generate and sign the CockroachDB node and client certificates. Read our Authentication docs to learn about other methods of signing certificates.
Create two directories:
$ mkdir certs my-safe-directory
Directory Description certs
You'll generate your CA certificate and all node and client certificates and keys in this directory. my-safe-directory
You'll generate your CA key in this directory and then reference the key when generating node and client certificates. Create the CA certificate and key pair:
$ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key
Create a client certificate and key pair for the root user:
$ cockroach cert create-client \ root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key
Upload the client certificate and key to the Kubernetes cluster as a secret:
$ kubectl create secret \ generic cockroachdb.client.root \ --from-file=certs
secret/cockroachdb.client.root created
Create the certificate and key pair for your CockroachDB nodes:
$ cockroach cert create-node \ localhost 127.0.0.1 \ cockroachdb-public \ cockroachdb-public.default \ cockroachdb-public.default.svc.cluster.local \ *.cockroachdb \ *.cockroachdb.default \ *.cockroachdb.default.svc.cluster.local \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key
Upload the node certificate and key to the Kubernetes cluster as a secret:
$ kubectl create secret \ generic cockroachdb.node \ --from-file=certs
secret/cockroachdb.node created
Check that the secrets were created on the cluster:
$ kubectl get secrets
NAME TYPE DATA AGE cockroachdb.client.root Opaque 3 41m cockroachdb.node Opaque 5 14s default-token-6qjdb kubernetes.io/service-account-token 3 4m
Initialize the cluster
Use the config file you downloaded to create the StatefulSet that automatically creates 3 pods, each running a CockroachDB node:
$ kubectl create -f cockroachdb-statefulset.yaml
serviceaccount/cockroachdb created role.rbac.authorization.k8s.io/cockroachdb created rolebinding.rbac.authorization.k8s.io/cockroachdb created service/cockroachdb-public created service/cockroachdb created poddisruptionbudget.policy/cockroachdb-budget created statefulset.apps/cockroachdb created
Initialize the CockroachDB cluster:
Confirm that three pods are
Running
successfully. Note that they will not be consideredReady
until after the cluster has been initialized:$ kubectl get pods
NAME READY STATUS RESTARTS AGE cockroachdb-0 0/1 Running 0 2m cockroachdb-1 0/1 Running 0 2m cockroachdb-2 0/1 Running 0 2m
Confirm that the persistent volumes and corresponding claims were created successfully for all three pods:
$ kubectl get pv
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-9e435563-fb2e-11e9-a65c-42010a8e0fca 100Gi RWO Delete Bound default/datadir-cockroachdb-0 standard 51m pvc-9e47d820-fb2e-11e9-a65c-42010a8e0fca 100Gi RWO Delete Bound default/datadir-cockroachdb-1 standard 51m pvc-9e4f57f0-fb2e-11e9-a65c-42010a8e0fca 100Gi RWO Delete Bound default/datadir-cockroachdb-2 standard 51m
Run
cockroach init
on one of the pods to complete the node startup process and have them join together as a cluster:$ kubectl exec -it cockroachdb-0 \ -- /cockroach/cockroach init \ --certs-dir=/cockroach/cockroach-certs
Cluster successfully initialized
Confirm that cluster initialization has completed successfully. The job should be considered successful and the Kubernetes pods should soon be considered
Ready
:$ kubectl get pods
NAME READY STATUS RESTARTS AGE cockroachdb-0 1/1 Running 0 3m cockroachdb-1 1/1 Running 0 3m cockroachdb-2 1/1 Running 0 3m
The CockroachDB Helm chart is compatible with Kubernetes versions 1.22 and earlier.
The CockroachDB Helm chart is currently not under active development, and no new features are planned. However, Cockroach Labs remains committed to fully supporting the Helm chart by addressing defects, providing security patches, and addressing breaking changes due to deprecations in Kubernetes APIs.
A deprecation notice for the Helm chart will be provided to customers a minimum of 6 months in advance of actual deprecation.
If you are running a secure Helm deployment on Kubernetes 1.22 and later, you must migrate away from using the Kubernetes CA for cluster authentication. For details, see Operate CockroachDB on Kubernetes.
Secure CockroachDB deployments on Amazon EKS via Helm are not yet supported.
Install the Helm client (version 3.0 or higher) and add the
cockroachdb
chart repository:$ helm repo add cockroachdb https://charts.cockroachdb.com/
"cockroachdb" has been added to your repositories
Update your Helm chart repositories to ensure that you're using the latest CockroachDB chart:
$ helm repo update
The cluster configuration is set in the Helm chart's values file.
Note:By default, the Helm chart specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload. For details on configuring your deployment, see Operate CockroachDB on Kubernetes.
Before deploying, modify some parameters in our Helm chart's values file:
- Create a local YAML file (e.g.,
my-values.yaml
) to specify your custom values. These will be used to override the defaults invalues.yaml
. 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
conf.cache
andconf.max-sql-memory
each to 1/4 of thememory
allocation specified instatefulset.resources.requests
andstatefulset.resources.limits
.Tip:For example, if you are allocating 8Gi of
memory
to each CockroachDB node, allocate 2Gi tocache
and 2Gi tomax-sql-memory
.conf: cache: "2Gi" max-sql-memory: "2Gi"
The Helm chart defaults to a secure deployment by automatically setting
tls.enabled
totrue
.Note:By default, the Helm chart will generate and sign 1 client and 1 node certificate to secure the cluster. To authenticate using your own CA, see Certificate management.
- Create a local YAML file (e.g.,
Install the CockroachDB Helm chart, specifying your custom values file.
Provide a "release" name to identify and track this particular deployment of the chart, and override the default values with those in
my-values.yaml
.Note:This tutorial uses
my-release
as the release name. If you use a different value, be sure to adjust the release name in subsequent commands.$ helm install my-release --values {custom-values}.yaml cockroachdb/cockroachdb
Behind the scenes, this command uses our
cockroachdb-statefulset.yaml
file 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.Confirm that CockroachDB cluster initialization has completed successfully, with the pods for CockroachDB showing
1/1
underREADY
and the pod for initialization showingCOMPLETED
underSTATUS
:$ kubectl get pods
NAME READY STATUS RESTARTS AGE my-release-cockroachdb-0 1/1 Running 0 8m my-release-cockroachdb-1 1/1 Running 0 8m my-release-cockroachdb-2 1/1 Running 0 8m my-release-cockroachdb-init-hxzsc 0/1 Completed 0 1h
Confirm that the persistent volumes and corresponding claims were created successfully for all three pods:
$ kubectl get pv
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-71019b3a-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-0 standard 11m pvc-7108e172-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-1 standard 11m pvc-710dcb66-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-2 standard 11m
Check that the secrets were created on the cluster:
$ kubectl get secrets
crdb-cockroachdb-ca-secret Opaque 2 23s crdb-cockroachdb-client-secret kubernetes.io/tls 3 22s crdb-cockroachdb-node-secret kubernetes.io/tls 3 23s
The StatefulSet configuration sets all CockroachDB nodes to log to stderr
, so if you ever need access to logs for a pod, use kubectl logs <podname>
rather than checking the log on the persistent volume.
Step 3. Use the built-in SQL client
To use the CockroachDB SQL client, first launch a secure pod running the cockroach
binary.
$ kubectl create \
-f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.15.1/examples/client-secure-operator.yaml
Get a shell into the pod and start the CockroachDB built-in SQL client:
$ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public
# Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # # Server version: CockroachDB CCL v21.1.0 (x86_64-unknown-linux-gnu, built 2021/04/23 13:54:57, go1.13.14) (same version as client) # Cluster ID: a96791d9-998c-4683-a3d3-edbf425bbf11 # # Enter \? for a brief introduction. # root@cockroachdb-public:26257/defaultdb>
Run some basic CockroachDB SQL statements:
> CREATE DATABASE bank;
> CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL);
> INSERT INTO bank.accounts VALUES (1, 1000.50);
> SELECT * FROM bank.accounts;
id | balance +----+---------+ 1 | 1000.50 (1 row)
Create a user with a password:
> CREATE USER roach WITH PASSWORD 'Q7gc8rEdS';
You will need this username and password to access the DB Console later.
Exit the SQL shell and pod:
> \q
$ kubectl create \
-f https://raw.githubusercontent.com/cockroachdb/cockroach/master/cloud/kubernetes/bring-your-own-certs/client.yaml
pod/cockroachdb-client-secure created
Get a shell into the pod and start the CockroachDB built-in SQL client:
$ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach-certs \ --host=cockroachdb-public
# Welcome to the cockroach SQL interface. # All statements must be terminated by a semicolon. # To exit: CTRL + D. # # Client version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Server version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Cluster ID: 256a8705-e348-4e3a-ab12-e1aba96857e4 # # Enter \? for a brief introduction. # root@cockroachdb-public:26257/defaultdb>
Tip:This pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other
cockroach
client commands (e.g.,cockroach node
), repeat step 2 using the appropriatecockroach
command.If you'd prefer to delete the pod and recreate it when needed, run
kubectl delete pod cockroachdb-client-secure
.Run some basic CockroachDB SQL statements:
> CREATE DATABASE bank;
> CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL);
> INSERT INTO bank.accounts VALUES (1, 1000.50);
> SELECT * FROM bank.accounts;
id | balance +----+---------+ 1 | 1000.50 (1 row)
Create a user with a password:
> CREATE USER roach WITH PASSWORD 'Q7gc8rEdS';
You will need this username and password to access the DB Console later.
Exit the SQL shell and pod:
> \q
From your local workstation, use our client-secure.yaml
file to launch a pod and keep it running indefinitely.
Download the file:
$ curl -OOOOOOOOO \ https://raw.githubusercontent.com/cockroachdb/helm-charts/master/examples/client-secure.yaml
In the file, set the following values:
spec.serviceAccountName: my-release-cockroachdb
spec.image: cockroachdb/cockroach: {your CockroachDB version}
spec.volumes[0].project.sources[0].secret.name: my-release-cockroachdb-client-secret
Use the file to launch a pod and keep it running indefinitely:
$ kubectl create -f client-secure.yaml
pod "cockroachdb-client-secure" created
Get a shell into the pod and start the CockroachDB built-in SQL client:
$ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=./cockroach-certs \ --host=my-release-cockroachdb-public
# Welcome to the cockroach SQL interface. # All statements must be terminated by a semicolon. # To exit: CTRL + D. # # Client version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Server version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Cluster ID: 256a8705-e348-4e3a-ab12-e1aba96857e4 # # Enter \? for a brief introduction. # root@my-release-cockroachdb-public:26257/defaultdb>
Tip:This pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other
cockroach
client commands (e.g.,cockroach node
), repeat step 2 using the appropriatecockroach
command.If you'd prefer to delete the pod and recreate it when needed, run
kubectl delete pod cockroachdb-client-secure
.Run some basic CockroachDB SQL statements:
> CREATE DATABASE bank;
> CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL);
> INSERT INTO bank.accounts VALUES (1, 1000.50);
> SELECT * FROM bank.accounts;
id | balance +----+---------+ 1 | 1000.50 (1 row)
Create a user with a password:
> CREATE USER roach WITH PASSWORD 'Q7gc8rEdS';
You will need this username and password to access the DB Console later.
Exit the SQL shell and pod:
> \q
Step 4. Access the DB Console
To access the cluster's DB Console:
On secure clusters, certain pages of the DB Console can only be accessed by
admin
users.Get a shell into the pod and start the CockroachDB built-in SQL client:
$ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public
$ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach-certs \ --host=cockroachdb-public
$ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach-certs \ --host=my-release-cockroachdb-public
Assign
roach
to theadmin
role (you only need to do this once):> GRANT admin TO roach;
Exit the SQL shell and pod:
> \q
In a new terminal window, port-forward from your local machine to the
cockroachdb-public
service:$ kubectl port-forward service/cockroachdb-public 8080
$ kubectl port-forward service/cockroachdb-public 8080
$ kubectl port-forward service/my-release-cockroachdb-public 8080
Forwarding from 127.0.0.1:8080 -> 8080
Note:Theport-forward
command must be run on the same machine as the web browser in which you want to view the DB Console. 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 configuringkubectl
locally and running the aboveport-forward
command on your local machine.Go to https://localhost:8080 and log in with the username and password you created earlier.
Note:If you are using Google Chrome, and you are getting an error about not being able to reach
localhost
because its certificate has been revoked, go to chrome://flags/#allow-insecure-localhost, enable "Allow invalid certificates for resources loaded from localhost", and then restart the browser. Enabling this Chrome feature degrades security for all sites running onlocalhost
, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily.In the UI, verify that the cluster is running as expected:
- View the Node List to ensure that all nodes successfully joined the cluster.
- Click the Databases tab on the left to verify that
bank
is listed.
Step 8. Stop the cluster
If you plan to restart the cluster, use the
minikube stop
command. This shuts down the minikube virtual machine but preserves all the resources you created:$ minikube stop
Stopping 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 delete
command. This shuts down and deletes the minikube virtual machine and all the resources you created, including persistent volumes:$ minikube delete
Deleting local Kubernetes cluster... Machine deleted.
Tip:To retain logs, copy them from each pod'sstderr
before 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:
- Replication & Rebalancing
- Fault Tolerance & Recovery
- Low Latency Multi-Region Deployment
- Serializable Transactions
- Cross-Cloud Migration
- Orchestration
- JSON Support
You might also want to learn how to orchestrate a production deployment of CockroachDB with Kubernetes.