> ## Documentation Index
> Fetch the complete documentation index at: https://www.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy a Local Cluster in Kubernetes

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

On top of CockroachDB's built-in automation, you can use a third-party <InternalLink path="kubernetes-overview">orchestration</InternalLink> 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](http://kubernetes.io/) orchestration system. Using either the CockroachDB [Helm](https://helm.sh/) 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.

<Note>
  To orchestrate a physically distributed cluster in production, see <InternalLink path="kubernetes-overview">Orchestrated Deployments</InternalLink>. To deploy a 30-day free CockroachDB Dedicated cluster instead of running CockroachDB yourself, see the <InternalLink version="cockroachcloud" path="quickstart">Quickstart</InternalLink>.
</Note>

<a id="best-practices" />

## Limitations

#### Kubernetes version

To deploy CockroachDB v24.1, Kubernetes 1.18 or higher is required. Cockroach Labs strongly recommends that you use a Kubernetes version that is [eligible for patch support by the Kubernetes project](https://kubernetes.io/releases).

#### Kubernetes Operator

* The CockroachDB Kubernetes Operator currently deploys clusters in a single region. For multi-region deployments using manual configs, see <InternalLink path="orchestrate-cockroachdb-with-kubernetes-multi-cluster">Orchestrate CockroachDB Across Multiple Kubernetes Clusters</InternalLink>.
* Using the Operator, you can give a new cluster an arbitrary number of [labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels). However, a cluster's labels cannot be modified after it is deployed. To track the status of this limitation, refer to [#993](https://github.com/cockroachdb/cockroach-operator/issues/993) in the Operator project's issue tracker.

#### Helm version

The CockroachDB Helm chart requires Helm 3.0 or higher. If you attempt to use an incompatible Helm version, an error like the following occurs:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
Error: UPGRADE FAILED: template: cockroachdb/templates/tests/client.yaml:6:14: executing "cockroachdb/templates/tests/client.yaml" at <.Values.networkPolicy.enabled>: nil pointer evaluating interface {}.enabled
```

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.

#### Network

Service Name Indication (SNI) is an extension to the TLS protocol which allows a client to indicate which hostname it is attempting to connect to at the start of the TCP handshake process. The server can present multiple certificates on the same IP address and TCP port number, and one server can serve multiple secure websites or API services even if they use different certificates.

Due to its order of operations, the PostgreSQL wire protocol's implementation of TLS is not compatible with SNI-based routing in the Kubernetes ingress controller. Instead, use a TCP load balancer for CockroachDB that is not shared with other services.

#### Resources

When starting Kubernetes, select machines with at least **4 vCPUs** and **16 GiB** of memory, and provision at least **2 vCPUs** and **8 Gi** of memory to CockroachDB per pod. These minimum settings are used by default in this deployment guide, and are appropriate for testing purposes only. On a production deployment, you should adjust the resource settings for your workload. For details, see <InternalLink path="configure-cockroachdb-kubernetes#memory-and-cpu">Resource management</InternalLink>.

<a id="storage" />

#### Storage

Kubernetes deployments use external persistent volumes that are often replicated by the provider. CockroachDB replicates data automatically, and this redundant layer of replication can impact performance. Using [local volumes](https://kubernetes.io/docs/concepts/storage/volumes#local) may improve performance.

## Before you begin

Before getting started, it's helpful to review some Kubernetes-specific terminology:

| Feature                                                                                                   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [minikube](http://kubernetes.io/docs/getting-started-guides/minikube)                                     | A tool commonly used to run a Kubernetes cluster on a local workstation.                                                                                                                                                                                                                                                                                                                                                                    |
| [pod](http://kubernetes.io/docs/user-guide/pods)                                                          | A pod is a group of one of more containers managed by Kubernetes. In this tutorial, all pods run on your local workstation. Each pod contains a single container that runs a single-node CockroachDB cluster. You'll start with 3 pods and grow to 4.                                                                                                                                                                                       |
| [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets)                   | 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.                                                                                                                                                                                                                                                            |
| [persistent volume](http://kubernetes.io/docs/user-guide/persistent-volumes)                              | A persistent volume is storage mounted in a pod and available to its containers. 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](http://kubernetes.io/docs/user-guide/persistent-volumes#persistentvolumeclaims) | When e pod is created, it requests a persistent volume claim to claim durable storage for its node.                                                                                                                                                                                                                                                                                                                                         |

## Step 1. Start Kubernetes

1. Follow the [Minikube documentation](https://kubernetes.io/docs/tasks/tools/install-minikube) to install the latest version of `minikube`, a hypervisor, and the `kubectl` command-line tool.
2. Start a local Kubernetes cluster:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   minikube start
   ```

## Step 2. Start CockroachDB

Choose a way to deploy and maintain the CockroachDB cluster:

* [CockroachDB Kubernetes Operator](https://github.com/cockroachdb/cockroach-operator) (recommended)
* [Helm](https://helm.sh/) package manager
* Manually apply our StatefulSet configuration and related files

### Install the Operator

1. Apply the [custom resource definition (CRD)](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources#customresourcedefinitions) for the Operator:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/crds.yaml
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   customresourcedefinition.apiextensions.k8s.io/crdbclusters.crdb.cockroachlabs.com created
   ```
2. 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.

   * To use these defaults, apply the Operator manifest without modifying it:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   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
   ```
3. To change these defaults:
   1. Download the Operator manifest:

      ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      curl -O https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml
      ```
   2. To use a custom namespace, edit all instances of `namespace: cockroach-operator-system` with your desired namespace.
   3. To limit the namespaces that will be monitored, set the `WATCH_NAMESPACE` environment variable in the `Deployment` pod spec. This can be set to a single namespace or a comma-delimited set of namespaces. When set, only those `CrdbCluster` resources in the supplied namespace(s) will be reconciled.
   4. Apply your local version of the Operator manifest to the cluster:

      ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      kubectl apply -f operator.yaml
      ```
4. Set your current namespace to the one used by the Operator. For example, to use the Operator's default namespace:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl config set-context --current --namespace=cockroach-operator-system
   ```
5. Validate that the Operator is running:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl get pods
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   NAME                                  READY   STATUS    RESTARTS   AGE
   cockroach-operator-6f7b86ffc4-9ppkv   1/1     Running   0          54s
   ```

### Initialize the cluster

<Note>
  After a cluster managed by the Kubernetes operator is initialized, its Kubernetes labels cannot be modified. For more details, refer to [Best practices](#best-practices).
</Note>

1. Download `example.yaml`, a custom resource that tells the Operator how to configure the Kubernetes cluster.

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ curl -O https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/examples/example.yaml
   ```

   By default, this custom resource 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 <InternalLink path="configure-cockroachdb-kubernetes">Configure the Cluster</InternalLink>.

<Note>
  By default, the Operator will generate and sign 1 client and 1 node certificate to secure the cluster. This means that if you do not provide a CA, a `cockroach`-generated CA is used. If you want to authenticate using your own CA, <InternalLink path="secure-cockroachdb-kubernetes#use-a-custom-ca">specify the generated secrets in the custom resource</InternalLink> **before** proceeding to the next step.
</Note>

2. Apply `example.yaml`:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl apply -f example.yaml
   ```

   The Operator will create a StatefulSet and initialize the nodes as a cluster.

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   crdbcluster.crdb.cockroachlabs.com/cockroachdb created
   ```
3. Check that the pods were created:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl get pods
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   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.

## Step 3. Use the built-in SQL client

To use the CockroachDB SQL client, first launch a secure pod running the `cockroach` binary.

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ kubectl create \
-f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/examples/client-secure-operator.yaml
```

1. Get a shell into the pod and start the CockroachDB <InternalLink path="cockroach-sql">built-in SQL client</InternalLink>:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl exec -it cockroachdb-client-secure \
   -- ./cockroach sql \
   --certs-dir=/cockroach/cockroach-certs \
   --host=cockroachdb-public
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   # 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>
   ```
2. Run some basic <InternalLink path="learn-cockroachdb-sql">CockroachDB SQL statements</InternalLink>:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE DATABASE bank;
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL);
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > INSERT INTO bank.accounts VALUES (1, 1000.50);
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > SELECT * FROM bank.accounts;
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
     id | balance
   +----+---------+
      1 | 1000.50
   (1 row)
   ```
3. <InternalLink path="create-user#create-a-user-with-a-password">Create a user with a password</InternalLink>:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS';
   ```

   You will need this username and password to access the DB Console later.
4. Exit the SQL shell and pod:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > \q
   ```

## Step 4. Access the DB Console

To access the cluster's <InternalLink path="ui-overview">DB Console</InternalLink>:

1. On secure clusters, <InternalLink path="ui-overview#db-console-access">certain pages of the DB Console</InternalLink> can only be accessed by `admin` users.

   Get a shell into the pod and start the CockroachDB <InternalLink path="cockroach-sql">built-in SQL client</InternalLink>:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl exec -it cockroachdb-client-secure \
   -- ./cockroach sql \
   --certs-dir=/cockroach/cockroach-certs \
   --host=cockroachdb-public
   ```
2. Assign `roach` to the `admin` role (you only need to do this once):

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > GRANT admin TO roach;
   ```
3. Exit the SQL shell and pod:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > \q
   ```
4. In a new terminal window, port-forward from your local machine to the `cockroachdb-public` service:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl port-forward service/cockroachdb-public 8080
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   Forwarding from 127.0.0.1:8080 -> 8080
   ```

<Note>
  The `port-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 configuring `kubectl` locally and running the above `port-forward` command on your local machine.
</Note>

5. Go to [https://localhost:8080](https://localhost:8080/) and log in with the username and password you created earlier.

   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](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 on `localhost`, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily.

6. In the UI, verify that the cluster is running as expected:
   * View the <InternalLink path="ui-cluster-overview-page#node-list">Node List</InternalLink> to ensure that all nodes successfully joined the cluster.
   * Click the **Databases** tab on the left to verify that `bank` is listed.

The CockroachDB Helm chart is compatible with all Kubernetes versions that are [supported by the Kubernetes project](https://kubernetes.io/releases) when cert-manager is used for mTLS.

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.

<Danger>
  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. The recommended approach is to use `cert-manager` for certificate management. For details, refer to <InternalLink path="secure-cockroachdb-kubernetes?filters=helm#deploy-cert-manager-for-mtls">Deploy cert-manager for mTLS</InternalLink>.
</Danger>

1. [Install the Helm client](https://helm.sh/docs/intro/install) (version 3.0 or higher) and add the `cockroachdb` chart repository:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ helm repo add cockroachdb https://charts.cockroachdb.com/
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   "cockroachdb" has been added to your repositories
   ```
2. Update your Helm chart repositories to ensure that you're using the [latest CockroachDB chart](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb/Chart.yaml):

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ helm repo update
   ```
3. The cluster configuration is set in the Helm chart's [values file](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb/values.yaml).

<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 <InternalLink path="configure-cockroachdb-kubernetes?filters=helm">Configure the Cluster</InternalLink>.
</Note>

Before deploying, modify some parameters in our Helm chart's [values file](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb/values.yaml):

1. Create a local YAML file (e.g., `my-values.yaml` ) to specify your custom values. These will be used to override the defaults in `values.yaml`.
2. 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` and `conf.max-sql-memory` each to 1/4 of the `memory` allocation specified in `statefulset.resources.requests` and `statefulset.resources.limits`.

<Tip>
  For example, if you are allocating 8Gi of `memory` to each CockroachDB node, allocate 2Gi to `cache` and 2Gi to `max-sql-memory`.
</Tip>

```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
conf:
  cache: "2Gi"
  max-sql-memory: "2Gi"
```

The Helm chart defaults to a secure deployment by automatically setting `tls.enabled` to `true`.

<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 <InternalLink path="secure-cockroachdb-kubernetes?filters=helm#use-a-custom-ca">Certificate management</InternalLink>.
</Note>

Refer to the [CockroachDB Helm chart's `values.yaml` template](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb/values.yaml).

4. 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.
</Note>

<Danger>
  To allow the CockroachDB pods to successfully deploy, do not set the [`--wait` flag](https://helm.sh/docs/intro/using_helm#helpful-options-for-installupgraderollback) when using Helm commands.
</Danger>

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ 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.

5. Confirm that CockroachDB cluster initialization has completed successfully, with the pods for CockroachDB showing `1/1` under `READY` and the pod for initialization showing `COMPLETED` under `STATUS`:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl get pods
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   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
   ```
6. Confirm that the persistent volumes and corresponding claims were created successfully for all three pods:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl get pv
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   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
   ```

<Tip>
  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.
</Tip>

## Step 3. Use the built-in SQL client

To use the CockroachDB SQL client, first launch a secure pod running the `cockroach` binary.

From your local workstation, use our [`client-secure.yaml`](https://github.com/cockroachdb/helm-charts/blob/master/examples/client-secure.yaml) file to launch a pod and keep it running indefinitely.

1. Download the file:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ curl -OOOOOOOOO \
   https://raw.githubusercontent.com/cockroachdb/helm-charts/master/examples/client-secure.yaml
   ```
2. 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`
3. Use the file to launch a pod and keep it running indefinitely:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl create -f client-secure.yaml
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   pod "cockroachdb-client-secure" created
   ```
4. Get a shell into the pod and start the CockroachDB <InternalLink path="cockroach-sql">built-in SQL client</InternalLink>:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl exec -it cockroachdb-client-secure \
   -- ./cockroach sql \
   --certs-dir=./cockroach-certs \
   --host=my-release-cockroachdb-public
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   # 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 <InternalLink path="cockroach-commands">`cockroach` client commands</InternalLink> (e.g., `cockroach node`), repeat step 2 using the appropriate `cockroach` command.

  If you'd prefer to delete the pod and recreate it when needed, run `kubectl delete pod cockroachdb-client-secure`.
</Tip>

5. Run some basic <InternalLink path="learn-cockroachdb-sql">CockroachDB SQL statements</InternalLink>:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE DATABASE bank;
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL);
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > INSERT INTO bank.accounts VALUES (1, 1000.50);
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > SELECT * FROM bank.accounts;
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
     id | balance
   +----+---------+
      1 | 1000.50
   (1 row)
   ```
6. <InternalLink path="create-user#create-a-user-with-a-password">Create a user with a password</InternalLink>:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS';
   ```

   You will need this username and password to access the DB Console later.
7. Exit the SQL shell and pod:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > \q
   ```

## Step 4. Access the DB Console

To access the cluster's <InternalLink path="ui-overview">DB Console</InternalLink>:

1. On secure clusters, <InternalLink path="ui-overview#db-console-access">certain pages of the DB Console</InternalLink> can only be accessed by `admin` users.

   Get a shell into the pod and start the CockroachDB <InternalLink path="cockroach-sql">built-in SQL client</InternalLink>:

   \$ kubectl exec -it cockroachdb-client-secure \ --./cockroach sql \ --certs-dir=/cockroach-certs \ --host=my-release-cockroachdb-public

2. Assign `roach` to the `admin` role (you only need to do this once):

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > GRANT admin TO roach;
   ```

3. Exit the SQL shell and pod:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > \q
   ```

4. In a new terminal window, port-forward from your local machine to the `cockroachdb-public` service:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl port-forward service/my-release-cockroachdb-public 8080
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   Forwarding from 127.0.0.1:8080 -> 8080
   ```

   The `port-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 configuring `kubectl` locally and running the above `port-forward` command on your local machine.

5. Go to [https://localhost:8080](https://localhost:8080/) and log in with the username and password you created earlier.

   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](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 on `localhost`, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily.

6. In the UI, verify that the cluster is running as expected:
   * View the <InternalLink path="ui-cluster-overview-page#node-list">Node List</InternalLink> to ensure that all nodes successfully joined the cluster.
   * Click the **Databases** tab on the left to verify that `bank` is listed.

### Configure the cluster

1. Download and modify our <InternalLink path="cockroach/cloud/kubernetes/bring-your-own-certs/cockroachdb-statefulset.yaml">StatefulSet configuration</InternalLink>:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ curl -O https://www.cockroachlabs.com/docs/files/cockroach/cloud/kubernetes/bring-your-own-certs/cockroachdb-statefulset.yaml
   ```
2. 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`](#create-certificates), use this secret name:

   ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   secret:
     secretName: cockroachdb.node
   ```
3. The StatefulSet configuration deploys CockroachDB into the `default` namespace. To use a different namespace, search for `kind: RoleBinding` and change its `subjects.namespace` property to the name of the namespace. Otherwise, a `failed to read secrets` error occurs when you attempt to follow the steps in [Initialize the cluster](#initialize-the-cluster).

<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. For details on configuring your deployment, see <InternalLink path="configure-cockroachdb-kubernetes?filters=manual">Configure the Cluster</InternalLink>.
</Note>

### 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 <InternalLink path="cockroach-cert">`cockroach cert` commands</InternalLink> to quickly generate and sign the CockroachDB node and client certificates. Read our <InternalLink path="authentication#using-digital-certificates-with-cockroachdb">Authentication</InternalLink> docs to learn about other methods of signing certificates.

1. Create two directories:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ 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. |

2. Create the CA certificate and key pair:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach cert create-ca \
   --certs-dir=certs \
   --ca-key=my-safe-directory/ca.key
   ```
3. Create a client certificate and key pair for the root user:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach cert create-client \
   root \
   --certs-dir=certs \
   --ca-key=my-safe-directory/ca.key
   ```
4. Upload the client certificate and key to the Kubernetes cluster as a secret:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl create secret \
   generic cockroachdb.client.root \
   --from-file=certs
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   secret/cockroachdb.client.root created
   ```
5. Create the certificate and key pair for your CockroachDB nodes:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ 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
   ```
6. Upload the node certificate and key to the Kubernetes cluster as a secret:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl create secret \
   generic cockroachdb.node \
   --from-file=certs
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   secret/cockroachdb.node created
   ```
7. Check that the secrets were created on the cluster:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl get secrets
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   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

1. Use the config file you downloaded to create the StatefulSet that automatically creates 3 pods, each running a CockroachDB node:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl create -f cockroachdb-statefulset.yaml
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   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
   ```
2. Initialize the CockroachDB cluster:
   1. Confirm that three pods are `Running` successfully. Note that they will not be considered `Ready` until after the cluster has been initialized:

      ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      $ kubectl get pods
      ```

      ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      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
      ```
   2. Confirm that the persistent volumes and corresponding claims were created successfully for all three pods:

      ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      $ kubectl get pv
      ```

      ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      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
      ```
   3. Run `cockroach init` on one of the pods to complete the node startup process and have them join together as a cluster:

      ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      $ kubectl exec -it cockroachdb-0 \
      -- /cockroach/cockroach init \
      --certs-dir=/cockroach/cockroach-certs
      ```

      ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      Cluster successfully initialized
      ```
   4. Confirm that cluster initialization has completed successfully. The job should be considered successful and the Kubernetes pods should soon be considered `Ready`:

      ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      $ kubectl get pods
      ```

      ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
      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
      ```

## Step 3. Use the built-in SQL client

To use the CockroachDB SQL client, first launch a secure pod running the `cockroach` binary.

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ kubectl create \
-f https://www.cockroachlabs.com/docs/files/cockroach/cloud/kubernetes/bring-your-own-certs/client.yaml
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
pod/cockroachdb-client-secure created
```

1. Get a shell into the pod and start the CockroachDB <InternalLink path="cockroach-sql">built-in SQL client</InternalLink>:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl exec -it cockroachdb-client-secure \
   -- ./cockroach sql \
   --certs-dir=/cockroach-certs \
   --host=cockroachdb-public
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   # 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>
   ```

   This pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other <InternalLink path="cockroach-commands">`cockroach` client commands</InternalLink> (e.g., `cockroach node`), repeat step 2 using the appropriate `cockroach` command.

   If you'd prefer to delete the pod and recreate it when needed, run `kubectl delete pod cockroachdb-client-secure`.

2. Run some basic <InternalLink path="learn-cockroachdb-sql">CockroachDB SQL statements</InternalLink>:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE DATABASE bank;
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL);
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > INSERT INTO bank.accounts VALUES (1, 1000.50);
   ```

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > SELECT * FROM bank.accounts;
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
     id | balance
   +----+---------+
      1 | 1000.50
   (1 row)
   ```

3. <InternalLink path="create-user#create-a-user-with-a-password">Create a user with a password</InternalLink>:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS';
   ```

   You will need this username and password to access the DB Console later.

4. Exit the SQL shell and pod:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > \q
   ```

## Step 4. Access the DB Console

To access the cluster's <InternalLink path="ui-overview">DB Console</InternalLink>:

1. On secure clusters, <InternalLink path="ui-overview#db-console-access">certain pages of the DB Console</InternalLink> can only be accessed by `admin` users.

   Get a shell into the pod and start the CockroachDB <InternalLink path="cockroach-sql">built-in SQL client</InternalLink>:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl exec -it cockroachdb-client-secure \
   -- ./cockroach sql \
   --certs-dir=/cockroach-certs \
   --host=cockroachdb-public
   ```

2. Assign `roach` to the `admin` role (you only need to do this once):

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > GRANT admin TO roach;
   ```

3. Exit the SQL shell and pod:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > \q
   ```

4. In a new terminal window, port-forward from your local machine to the `cockroachdb-public` service:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ kubectl port-forward service/cockroachdb-public 8080
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   Forwarding from 127.0.0.1:8080 -> 8080
   ```

   The `port-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 configuring `kubectl` locally and running the above `port-forward` command on your local machine.

5. Go to [https://localhost:8080](https://localhost:8080/) and log in with the username and password you created earlier.

   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](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 on `localhost`, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily.

6. In the UI, verify that the cluster is running as expected:
   * View the <InternalLink path="ui-cluster-overview-page#node-list">Node List</InternalLink> to ensure that all nodes successfully joined the cluster.
   * Click the **Databases** tab on the left to verify that `bank` is listed.

## Step 5. 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:

  ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
  minikube stop
  ```

  ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
  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:

  ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
  minikube delete
  ```

  ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
  Deleting local Kubernetes cluster...
  Machine deleted.
  ```

<Tip>
  To retain logs, copy them from each pod's `stderr` before deleting the cluster and all its resources. To access a pod's standard error stream, run `kubectl logs <podname>`.
</Tip>

## See also

Explore other CockroachDB benefits and features:

* <InternalLink path="demo-replication-and-rebalancing">Replication & Rebalancing</InternalLink>
* <InternalLink path="demo-fault-tolerance-and-recovery">Fault Tolerance & Recovery</InternalLink>
* <InternalLink path="demo-low-latency-multi-region-deployment">Low Latency Multi-Region Deployment</InternalLink>
* <InternalLink path="demo-serializable">Serializable Transactions</InternalLink>
* <InternalLink path="demo-automatic-cloud-migration">Cross-Cloud Migration</InternalLink>
* <InternalLink path="orchestrate-a-local-cluster-with-kubernetes-insecure">Orchestration</InternalLink>
* <InternalLink path="demo-json-support">JSON Support</InternalLink>

You might also want to learn how to <InternalLink path="deploy-cockroachdb-with-kubernetes">orchestrate a production deployment of CockroachDB with Kubernetes</InternalLink>.
