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

# Deploy CockroachDB On-Premises

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>;
};

This tutorial shows you how to manually deploy a secure multi-node CockroachDB cluster on multiple machines, using [HAProxy](http://www.haproxy.org/) load balancers to distribute client traffic.

If you are only testing CockroachDB, or you are not concerned with protecting network communication with TLS encryption, you can use an insecure cluster instead. Select **Insecure** above for instructions.

<Tip>
  To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the <InternalLink version="cockroachcloud" path="quickstart">Cloud Quickstart</InternalLink>.
</Tip>

## Before you begin

### Requirements

* You must have <InternalLink path="install-cockroachdb">CockroachDB installed</InternalLink> locally. This is necessary for generating and managing your deployment's certificates.

* You must have [SSH access](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2) to each machine. This is necessary for distributing and starting CockroachDB binaries.

* Your network configuration must allow TCP communication on the following ports:
  * `26257` for intra-cluster and client-cluster communication
  * `8080` to expose your DB Console

* Carefully review the <InternalLink path="recommended-production-settings">Production Checklist</InternalLink>, including supported hardware and software, and the recommended <InternalLink path="topology-patterns">Topology Patterns</InternalLink>.

* Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine.

* To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see <InternalLink path="cockroach-start#store">Start a Node</InternalLink>.

  If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`.

* When starting each node, use the <InternalLink path="cockroach-start#locality">`--locality`</InternalLink> flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes.

* When deploying in a single availability zone:
  * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the <InternalLink path="configure-replication-zones#view-the-default-replication-zone">`default` 3-way replication factor</InternalLink>. In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority.
  * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and <InternalLink path="configure-replication-zones#edit-the-default-replication-zone">increase the `default` replication factor for user data</InternalLink> to 5. The replication factor for <InternalLink path="configure-replication-zones#create-a-replication-zone-for-a-system-range">important internal data</InternalLink> is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority.

* When deploying across multiple availability zones:
  * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas.
  * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption.

* When deploying across multiple regions:
  * To be able to tolerate the failure of 1 entire region, use at least 3 regions.

### Recommendations

* Decide how you want to access your DB Console:

| Access Level      | Description                                                                                                                                                           |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Partially open    | Set a firewall rule to allow only specific IP addresses to communicate on port `8080`.                                                                                |
| Completely open   | Set a firewall rule to allow all IP addresses to communicate on port `8080`.                                                                                          |
| Completely closed | Set a firewall rule to disallow all communication on port `8080`. In this case, a machine with SSH access to a node could use an SSH tunnel to access the DB Console. |

## Step 1. Synchronize clocks

CockroachDB requires moderate levels of <InternalLink path="recommended-production-settings#clock-synchronization">clock synchronization</InternalLink> to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed (500ms by default), it spontaneously shuts down. This avoids the risk of consistency anomalies, but it's best to prevent clocks from drifting too far in the first place by running clock synchronization software on each node.

[`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well.

1. SSH to the first machine.
2. Disable `timesyncd`, which tends to be active by default on some Linux distributions:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ sudo timedatectl set-ntp no
   ```

   Verify that `timesyncd` is off:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ timedatectl
   ```

   Look for `Network time on: no` or `NTP enabled: no` in the output.
3. Install the `ntp` package:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ sudo apt-get install ntp
   ```
4. Stop the NTP daemon:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ sudo service ntp stop
   ```
5. Sync the machine's clock with Google's NTP service:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ sudo ntpd -b time.google.com
   ```

   To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   server time1.google.com iburst
   server time2.google.com iburst
   server time3.google.com iburst
   server time4.google.com iburst
   ```

   Restart the NTP daemon:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ sudo service ntp start
   ```

<Note>
  We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the <InternalLink path="recommended-production-settings#considerations">Production Checklist</InternalLink> for details.
</Note>

6. Verify that the machine is using a Google NTP server:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ sudo ntpq -p
   ```

   The active NTP server will be marked with an asterisk.
7. Repeat these steps for each machine where a CockroachDB node will run.

## Step 2. Generate certificates

You can use `cockroach cert` commands or <InternalLink path="create-security-certificates-openssl">`openssl` commands</InternalLink> to generate security certificates. This section features the `cockroach cert` commands.

Locally, you'll need to <InternalLink path="cockroach-cert">create the following certificates and keys</InternalLink>:

* A certificate authority (CA) key pair ( `ca.crt` and `ca.key` ).
* A node key pair for each node, issued to its IP addresses and any common names the machine uses, as well as to the IP addresses and common names for machines running load balancers.
* A client key pair for the `root` user. You'll use this to run a sample workload against the cluster as well as some `cockroach` client commands from your local machine.

<Tip>
  Before beginning, it's useful to collect each of your machine's internal and external IP addresses, as well as any server names you want to issue certificates for.
</Tip>

1. <InternalLink path="install-cockroachdb">Install CockroachDB</InternalLink> on your local machine, if you haven't already.
2. Create two directories:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ mkdir certs
   ```

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ mkdir my-safe-directory
   ```

   * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes.
   * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. After that, you'll keep the key safe and secret; you will not upload it to your nodes.
3. Create the CA certificate and key:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach cert create-ca \
   --certs-dir=certs \
   --ca-key=my-safe-directory/ca.key
   ```
4. Create the certificate and key for the first node, issued to all common names you might use to refer to the node as well as to the load balancer instances:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach cert create-node \
   <node1 internal IP address> \
   <node1 external IP address> \
   <node1 hostname>  \
   <other common names for node1> \
   localhost \
   127.0.0.1 \
   <load balancer IP address> \
   <load balancer hostname>  \
   <other common names for load balancer instances> \
   --certs-dir=certs \
   --ca-key=my-safe-directory/ca.key
   ```
5. Upload the CA certificate and node certificate and key to the first node:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ ssh <username>@<node1 address "mkdir certs"
   ```

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ scp certs/ca.crt \
   certs/node.crt \
   certs/node.key \
   <username>@<node1 address:~/certs
   ```
6. Delete the local copy of the node certificate and key:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ rm certs/node.crt certs/node.key
   ```

<Note>
  This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key`. As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag.
</Note>

7. Create the certificate and key for the second node, issued to all common names you might use to refer to the node as well as to the load balancer instances:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach cert create-node \
   <node2 internal IP address> \
   <node2 external IP address> \
   <node2 hostname>  \
   <other common names for node2> \
   localhost \
   127.0.0.1 \
   <load balancer IP address> \
   <load balancer hostname>  \
   <other common names for load balancer instances> \
   --certs-dir=certs \
   --ca-key=my-safe-directory/ca.key
   ```
8. Upload the CA certificate and node certificate and key to the second node:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ ssh <username>@<node2 address "mkdir certs"
   ```

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ scp certs/ca.crt \
   certs/node.crt \
   certs/node.key \
   <username>@<node2 address:~/certs
   ```
9. Repeat steps 6 - 8 for each additional node.
10. Create a client certificate and key 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
    ```
11. Upload the CA certificate and client certificate and key to the machine where you will run a sample workload:

    ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
    $ ssh <username>@<workload address "mkdir certs"
    ```

    ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
    $ scp certs/ca.crt \
    certs/client.root.crt \
    certs/client.root.key \
    <username>@<workload address:~/certs
    ```

    In later steps, you'll also use the `root` user's certificate to run <InternalLink path="cockroach-commands">`cockroach`</InternalLink> client commands from your local machine. If you might also want to run `cockroach` client commands directly on a node (e.g., for local debugging), you'll need to copy the `root` user's certificate and key to that node as well.

<Note>
  On accessing the DB Console in a later step, your browser will consider the CockroachDB-created certificate invalid and you’ll need to click through a warning message to get to the UI. You can avoid this issue by <InternalLink path="create-security-certificates-custom-ca#accessing-the-db-console-for-a-secure-cluster">using a certificate issued by a public CA</InternalLink>.
</Note>

## Step 3. Start nodes

You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd).

For each initial node of your cluster, complete the following steps:

<Note>
  After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step.
</Note>

1. Visit <InternalLink version="releases" path="index">Releases</InternalLink> and download the full binary of CockroachDB to the node.
2. On the node, follow the instructions to <InternalLink path="install-cockroachdb">install CockroachDB</InternalLink>.
3. Run the <InternalLink path="cockroach-start">`cockroach start`</InternalLink> command:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach start \
   --certs-dir=certs \
   --advertise-addr=<node1 address \
   --join=<node1 address,<node2 address,<node3 address \
   --cache=.25 \
   --max-sql-memory=.25 \
   --background
   ```

   This command primes the node to start, using the following flags:

| Flag                         | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--certs-dir`                | Specifies the directory where you placed the `ca.crt` file and the `node.crt` and `node.key` files for the node.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `--advertise-addr`           | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`.  This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses).  In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see <InternalLink path="recommended-production-settings#networking">Networking</InternalLink>.                                                                  |
| `--join`                     | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising.                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `--cache` `--max-sql-memory` | Increases the node's cache size to 25% of available system memory to improve read performance. The capacity for in-memory SQL processing defaults to 25% of system memory but can be raised, if necessary, to increase the number of simultaneous client connections allowed by the node as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. For more details, see <InternalLink path="recommended-production-settings#cache-and-sql-memory-size">Cache and SQL Memory Size</InternalLink>. |
| `--background`               | Starts the node in the background so you gain control of the terminal to issue more commands.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see <InternalLink path="cockroach-start#locality">Locality</InternalLink>.

For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=<node1 address:8080`. To set these options manually, see <InternalLink path="cockroach-start">Start a Node</InternalLink>.

Repeat these steps for each additional node that you want in your cluster.

For each initial node of your cluster, complete the following steps:

After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step.

1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user.
2. <InternalLink path="install-cockroachdb">Install CockroachDB for Linux</InternalLink>.
3. Create the Cockroach directory:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ mkdir /var/lib/cockroach
   ```
4. Create a Unix user named `cockroach`:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ useradd cockroach
   ```
5. Move the `certs` directory to the `cockroach` directory.

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ mv certs /var/lib/cockroach/
   ```
6. Change the ownership of the `cockroach` directory to the user `cockroach`:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ chown -R cockroach /var/lib/cockroach
   ```
7. Download the [sample configuration template](https://raw.githubusercontent.com/cockroachlabs/docs/main/src/current/_includes/v24.3/prod-deployment/securecockroachdb.service) and save the file in the `/etc/systemd/system/` directory:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   curl -o securecockroachdb.service https://raw.githubusercontent.com/cockroachlabs/docs/main/src/current/_includes/v23.2/prod-deployment/securecockroachdb.service
   ```

   Alternatively, you can create the file yourself and copy the script into it:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   [Unit]
   Description=Cockroach Database cluster node
   Requires=network.target
   [Service]
   Type=notify
   WorkingDirectory=/var/lib/cockroach
   ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr=<node1 address --join=<node1 address,<node2 address,<node3 address --cache=.25 --max-sql-memory=.25
   TimeoutStopSec=300
   Restart=always
   RestartSec=10
   StandardOutput=syslog
   StandardError=syslog
   SyslogIdentifier=cockroach
   User=cockroach
   [Install]
   WantedBy=default.target
   ```
8. In the sample configuration template, specify values for the following flags:

| Flag               | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`.  This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses).  In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see <InternalLink path="recommended-production-settings#networking">Networking</InternalLink>. |
| `--join`           | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising.                                                                                                                                                                                                                                                                                                                                                               |

When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see <InternalLink path="cockroach-start#locality">Locality</InternalLink>.

For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=localhost:8080`. To set these options manually, see <InternalLink path="cockroach-start">Start a Node</InternalLink>.
9\. Start the CockroachDB cluster:

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

10. Configure `systemd` to start CockroachDB automatically after a reboot:

    ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
    systemctl enable securecockroachdb
    ```
11. Repeat these steps for each additional node that you want in your cluster.

<Note>
  `systemd` handles node restarts in case of node failure. To stop a node without `systemd` restarting it, run `systemctl stop securecockroachdb`
</Note>

## Step 4. Initialize the cluster

On your local machine, run the <InternalLink path="cockroach-init">`cockroach init`</InternalLink> command to complete the node startup process and have them join together as a cluster:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach init --certs-dir=certs --host=<address of any node on --join list
```

After running this command, each node prints helpful details to the <InternalLink path="cockroach-start#standard-output">standard output</InternalLink>, such as the CockroachDB version, the URL for the DB Console, and the SQL URL for clients.

## Step 5. Test the cluster

CockroachDB replicates and distributes data behind-the-scenes and uses a [Gossip protocol](https://wikipedia.org/wiki/Gossip_protocol) to enable each node to locate data across the cluster. Once a cluster is live, any node can be used as a SQL gateway.

When using a load balancer, you should issue commands directly to the load balancer, which then routes traffic to the nodes.

Use the <InternalLink path="cockroach-sql">built-in SQL client</InternalLink> locally as follows:

1. On your local machine, launch the built-in SQL client, with the `--host` flag set to the address of the load balancer:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach sql --certs-dir=certs --host=<address of load balancer
   ```
2. Create a `securenodetest` database:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > CREATE DATABASE securenodetest;
   ```
3. View the cluster's databases, which will include `securenodetest`:

   ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   > SHOW DATABASES;
   ```

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   +--------------------+
   |      Database      |
   +--------------------+
   | crdb_internal      |
   | information_schema |
   | securenodetest     |
   | pg_catalog         |
   | system             |
   +--------------------+
   (5 rows)
   ```
4. Use `\q` to exit the SQL shell.

## Step 6. Set up load balancing

Each CockroachDB node is an equally suitable SQL gateway to your cluster, but to ensure client performance and reliability, it's important to use load balancing:

* **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second).
* **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. In cases where a node fails, the load balancer redirects client traffic to available nodes.

<Tip>
  With a single load balancer, client connections are resilient to node failure, but the load balancer itself is a point of failure. It's therefore best to make load balancing resilient as well by using multiple load balancing instances, with a mechanism like floating IPs or DNS to select load balancers for clients.
</Tip>

[HAProxy](http://www.haproxy.org/) is one of the most popular open-source TCP load balancers, and CockroachDB includes a built-in command for generating a configuration file that is preset to work with your running cluster, so we feature that tool here.

1. On your local machine, run the <InternalLink path="cockroach-gen">`cockroach gen haproxy`</InternalLink> command with the `--host` flag set to the address of any node and security flags pointing to the CA cert and the client cert and key:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   cockroach gen haproxy \
   --certs-dir=certs \
   --host=<address of any node
   ```

   By default, the generated configuration file is called `haproxy.cfg` and looks as follows, with the `server` addresses pre-populated correctly:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   global
     maxconn 4096

   defaults
       mode                tcp
       # Timeout values should be configured for your specific use.
       # See: https://cbonte.github.io/haproxy-dconv/1.8/configuration.html#4-timeout%20connect
       timeout connect     10s
       timeout client      1m
       timeout server      1m
       # TCP keep-alive on client side. Server already enables them.
       option              clitcpka

   listen psql
       bind :26257
       mode tcp
       balance roundrobin
       option httpchk GET /health?ready=1
       server cockroach1 <node1 address>:26257 check port 8080
       server cockroach2 <node2 address>:26257 check port 8080
       server cockroach3 <node3 address>:26257 check port 8080
   ```

   The file is preset with the minimal [configurations](http://cbonte.github.io/haproxy-dconv/1.7/configuration) needed to work with your running cluster:

| Field                                               | Description                                                                                                                                                                                                                                                                                                                                                                                          |
| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `timeout connect` `timeout client` `timeout server` | Timeout values that should be suitable for most deployments.                                                                                                                                                                                                                                                                                                                                         |
| `bind`                                              | The port that HAProxy listens on. This is the port clients will connect to and thus needs to be allowed by your network configuration.  This tutorial assumes HAProxy is running on a separate machine from CockroachDB nodes. If you run HAProxy on the same machine as a node (not recommended), you'll need to change this port, as `26257` is likely already being used by the CockroachDB node. |
| `balance`                                           | The balancing algorithm. This is set to `roundrobin` to ensure that connections get rotated amongst nodes (connection 1 on node 1, connection 2 on node 2, etc.). Check the [HAProxy Configuration Manual](http://cbonte.github.io/haproxy-dconv/1.7/configuration#4-balance) for details about this and other balancing algorithms.                                                                 |
| `option httpchk`                                    | The HTTP endpoint that HAProxy uses to check node health. <InternalLink path="monitoring-and-alerting">`/health?ready=1`</InternalLink> ensures that HAProxy doesn't direct traffic to nodes that are live but not ready to receive requests.                                                                                                                                                        |
| `server`                                            | For each included node, this field specifies the address the node advertises to other nodes in the cluster, i.e., the addressed pass in the <InternalLink path="cockroach-start#networking">`--advertise-addr` flag</InternalLink> on node startup. Make sure hostnames are resolvable and IP addresses are routable from HAProxy.                                                                   |

<Note>
  For full details on these and other configuration settings, see the [HAProxy Configuration Manual](http://cbonte.github.io/haproxy-dconv/1.7/configuration).
</Note>

2. Upload the `haproxy.cfg` file to the machine where you want to run HAProxy:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   scp haproxy.cfg <username>@<haproxy address:~/
   ```
3. SSH to the machine where you want to run HAProxy.
4. Install HAProxy:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   apt-get install haproxy
   ```
5. Start HAProxy, with the `-f` flag pointing to the `haproxy.cfg` file:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   haproxy -f haproxy.cfg
   ```
6. Repeat these steps for each additional instance of HAProxy you want to run.

## Step 7. Run a sample workload

CockroachDB comes with a number of <InternalLink path="cockroach-workload">built-in workloads</InternalLink> for simulating client traffic. This step features CockroachDB's version of the [TPC-C](http://www.tpc.org/tpcc) workload.

<Note>
  Be sure that you have configured your network to allow traffic from the application to the load balancer. In this case, you will run the sample workload on one of your machines. The traffic source should therefore be the **internal (private)** IP address of that machine.
</Note>

For comprehensive guidance on benchmarking CockroachDB with TPC-C, refer to <InternalLink path="performance-benchmarking-with-tpcc-local">Performance Benchmarking</InternalLink>.

1. SSH to the machine where you want to run the sample TPC-C workload.

   This should be a machine that is not running a CockroachDB node, and it should already have a `certs` directory containing `ca.crt`, `client.root.crt`, and `client.root.key` files.
2. <InternalLink path="install-cockroachdb">Install CockroachDB for Linux</InternalLink>.
3. Use the <InternalLink path="cockroach-workload">`cockroach workload`</InternalLink> command to load the initial schema and data, pointing it at the IP address of the load balancer:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach workload init tpcc \
   'postgresql://root@<IP ADDRESS OF LOAD BALANCER>:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key'
   ```
4. Use the `cockroach workload` command to run the workload for 10 minutes:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach workload run tpcc \
   --duration=10m \
   'postgresql://root@<IP ADDRESS OF LOAD BALANCER>:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key'
   ```

   You'll see per-operation statistics print to standard output every second:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)
         1s        0         1443.4         1494.8      4.7      9.4     27.3     67.1 transfer
         2s        0         1686.5         1590.9      4.7      8.1     15.2     28.3 transfer
         3s        0         1735.7         1639.0      4.7      7.3     11.5     28.3 transfer
         4s        0         1542.6         1614.9      5.0      8.9     12.1     21.0 transfer
         5s        0         1695.9         1631.1      4.7      7.3     11.5     22.0 transfer
         6s        0         1569.2         1620.8      5.0      8.4     11.5     15.7 transfer
         7s        0         1614.6         1619.9      4.7      8.1     12.1     16.8 transfer
         8s        0         1344.4         1585.6      5.8     10.0     15.2     31.5 transfer
         9s        0         1351.9         1559.5      5.8     10.0     16.8     54.5 transfer
        10s        0         1514.8         1555.0      5.2      8.1     12.1     16.8 transfer
   ...
   ```

   After the specified duration (10 minutes in this case), the workload will stop and you'll see totals printed to standard output:

   ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   _elapsed___errors_____ops(total)___ops/sec(cum)__avg(ms)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)__result
     600.0s        0         823902         1373.2      5.8      5.5     10.0     15.2    209.7
   ```

<Tip>
  For more `tpcc` options, use `cockroach workload run tpcc --help`. For details about other workloads built into the `cockroach` binary, use `cockroach workload --help`.
</Tip>

5. To monitor the load generator's progress, open the <InternalLink path="ui-overview">DB Console</InternalLink> by pointing a browser to the address in the `admin` field in the standard output of any node on startup.

   Since the load generator is pointed at the load balancer, the connections will be evenly distributed across nodes. To verify this, click **Metrics** on the left, select the **SQL** dashboard, and then check the **SQL Connections** graph. You can use the **Graph** menu to filter the graph for specific nodes.

## Step 8. Monitor the cluster

Despite CockroachDB's various <InternalLink path="frequently-asked-questions">built-in safeguards against failure</InternalLink>, it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention.

For details about available monitoring options and the most important events and metrics to alert on, see <InternalLink path="monitoring-and-alerting">Monitoring and Alerting</InternalLink>.

## Step 9. Scale the cluster

You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd).

For each additional node you want to add to the cluster, complete the following steps:

1. SSH to the machine where you want the node to run.
2. <InternalLink path="install-cockroachdb">Install CockroachDB for Linux</InternalLink>.
3. Run the <InternalLink path="cockroach-start">`cockroach start`</InternalLink> command, passing the new node's address as the `--advertise-addr` flag and pointing `--join` to the three existing nodes (also include `--locality` if you set it earlier).

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   $ cockroach start \
   --certs-dir=certs \
   --advertise-addr=<node4 address \
   --join=<node1 address,<node2 address,<node3 address \
   --cache=.25 \
   --max-sql-memory=.25 \
   --background
   ```
4. Update your load balancer to recognize the new node.

For each additional node you want to add to the cluster, complete the following steps:

1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user.
2. <InternalLink path="install-cockroachdb">Install CockroachDB for Linux</InternalLink>.
3. Create the Cockroach directory:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   mkdir /var/lib/cockroach
   ```
4. Create a Unix user named `cockroach`:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   useradd cockroach
   ```
5. Move the `certs` directory to the `cockroach` directory.

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   mv certs /var/lib/cockroach/
   ```
6. Change the ownership of the `cockroach` directory to the user `cockroach`:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   chown -R cockroach /var/lib/cockroach
   ```
7. Download the [sample configuration template](https://raw.githubusercontent.com/cockroachlabs/docs/master/_includes/v24.3/prod-deployment/securecockroachdb.service):

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   curl -o securecockroachdb.service https://raw.githubusercontent.com/cockroachlabs/docs/master/_includes/v24.3/prod-deployment/securecockroachdb.service
   ```

   Alternatively, you can create the file yourself and copy the script into it:

   ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
   [Unit]
   Description=Cockroach Database cluster node
   Requires=network.target
   [Service]
   Type=notify
   WorkingDirectory=/var/lib/cockroach
   ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr=<node1 address --join=<node1 address,<node2 address,<node3 address --cache=.25 --max-sql-memory=.25
   TimeoutStopSec=300
   Restart=always
   RestartSec=10
   StandardOutput=syslog
   StandardError=syslog
   SyslogIdentifier=cockroach
   User=cockroach
   [Install]
   WantedBy=default.target
   ```

   Save the file in the `/etc/systemd/system/` directory.
8. Customize the sample configuration template for your deployment:

   Specify values for the following flags in the sample configuration template:

| Flag               | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`.  This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses).  In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see <InternalLink path="recommended-production-settings#networking">Networking</InternalLink>. |
| `--join`           | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising.                                                                                                                                                                                                                                                                                                                                                               |

9. Repeat these steps for each additional node that you want in your cluster.

## Step 10. Use the cluster

Now that your deployment is working, you can:

1. <InternalLink path="sql-statements">Implement your data model</InternalLink>.
2. <InternalLink path="create-user">Create users</InternalLink> and <InternalLink path="grant">grant them privileges</InternalLink>.
3. <InternalLink path="install-client-drivers">Connect your application</InternalLink>. Be sure to connect your application to the load balancer, not to a CockroachDB node.
4. <InternalLink path="take-full-and-incremental-backups">Take backups</InternalLink> of your data.

You may also want to adjust the way the cluster replicates data. For example, by default, a multi-node cluster replicates all data 3 times; you can change this replication factor or create additional rules for replicating individual databases and tables differently. For more information, see <InternalLink path="configure-replication-zones">Replication Controls</InternalLink>.

<Danger>
  When running a cluster of 5 nodes or more, it's safest to <InternalLink path="configure-replication-zones#create-a-replication-zone-for-a-system-range">increase the replication factor for important internal data</InternalLink> to 5, even if you do not do so for user data. For the cluster as a whole to remain available, the ranges for this internal data must always retain a majority of their replicas.
</Danger>

## See also

* <InternalLink path="recommended-production-settings">Production Checklist</InternalLink>
* <InternalLink path="manual-deployment">Manual Deployment</InternalLink>
* <InternalLink path="kubernetes-overview">Orchestrated Deployment</InternalLink>
* <InternalLink path="monitoring-and-alerting">Monitoring and Alerting</InternalLink>
* <InternalLink path="performance-benchmarking-with-tpcc-small">Performance Benchmarking</InternalLink>
* <InternalLink path="performance-best-practices-overview">Performance Tuning</InternalLink>
* <InternalLink path="start-a-local-cluster">Local Deployment</InternalLink>
