This tutorial shows you how to manually deploy a secure multi-node CockroachDB cluster on multiple machines, using HAProxy 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.
Before you begin
Requirements
Carefully review the Production Checklist and recommended Topology Patterns.
You must have CockroachDB installed locally. This is necessary for generating and managing your deployment's certificates.
You must have SSH access to each machine. This is necessary for distributing and starting CockroachDB binaries.
Your network configuration must allow TCP communication on the following ports:
26257for intra-cluster and client-cluster communication8080to expose your Admin UI
Recommendations
Decide how you want to access your Admin UI:
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 Admin UI.
Step 1. Synchronize clocks
CockroachDB requires moderate levels of clock synchronization 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 should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well.
SSH to the first machine.
Disable
timesyncd, which tends to be active by default on some Linux distributions:$ sudo timedatectl set-ntp noVerify that
timesyncdis off:$ timedatectlLook for
Network time on: noorNTP enabled: noin the output.Install the
ntppackage:$ sudo apt-get install ntpStop the NTP daemon:
$ sudo service ntp stopSync the machine's clock with Google's NTP service:
$ sudo ntpd -b time.google.comTo make this change permanent, in the
/etc/ntp.conffile, remove or comment out any lines starting withserverorpooland add the following lines:server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburstRestart the NTP daemon:
$ sudo service ntp startNote:We recommend Google's NTP service because it handles "smearing" the leap second. 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 Production Checklist for details.
Verify that the machine is using a Google NTP server:
$ sudo ntpq -pThe active NTP server will be marked with an asterisk.
Repeat these steps for each machine where a CockroachDB node will run.
Step 2. Generate certificates
You can use either cockroach cert commands or openssl commands to generate security certificates. This section features the cockroach cert commands.
Locally, you'll need to create the following certificates and keys:
- A certificate authority (CA) key pair (
ca.crtandca.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
rootuser. You'll use this to run a sample workload against the cluster as well as somecockroachclient commands from your local machine.
Install CockroachDB on your local machine, if you haven't already.
Create two directories:
$ mkdir certs$ mkdir my-safe-directorycerts: 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.
Create the CA certificate and key:
$ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.keyCreate 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:
$ 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.keyUpload the CA certificate and node certificate and key to the first node:
$ ssh <username>@<node1 address> "mkdir certs"$ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ <username>@<node1 address>:~/certsDelete the local copy of the node certificate and key:
$ rm certs/node.crt certs/node.keyNote:This is necessary because the certificates and keys for additional nodes will also be named
node.crtandnode.key. As an alternative to deleting these files, you can run the nextcockroach cert create-nodecommands with the--overwriteflag.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:
$ 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.keyUpload the CA certificate and node certificate and key to the second node:
$ ssh <username>@<node2 address> "mkdir certs"$ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ <username>@<node2 address>:~/certsRepeat steps 6 - 8 for each additional node.
Create a client certificate and key for the
rootuser:$ cockroach cert create-client \ root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.keyUpload the CA certificate and client certificate and key to the machine where you will run a sample workload:
$ ssh <username>@<workload address> "mkdir certs"$ scp certs/ca.crt \ certs/client.root.crt \ certs/client.root.key \ <username>@<workload address>:~/certsIn later steps, you'll also use the
rootuser's certificate to runcockroachclient commands from your local machine. If you might also want to runcockroachclient commands directly on a node (e.g., for local debugging), you'll need to copy therootuser's certificate and key to that node as well.
On accessing the Admin UI 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 using a certificate issued by a public CA.
Step 3. Start nodes
You can start the nodes manually or automate the process using systemd.
For each initial node of your cluster, complete the following steps:
SSH to the machine where you want the node to run.
Download the CockroachDB archive for Linux, and extract the binary:
$ curl https://binaries.cockroachdb.com/cockroach-v19.1.11.linux-amd64.tgz \ | tar -xzCopy the binary into the
PATH:$ cp -i cockroach-v19.1.11.linux-amd64/cockroach /usr/local/bin/If you get a permissions error, prefix the command with
sudo.Run the
cockroach startcommand:$ cockroach start \ --certs-dir=certs \ --advertise-addr=<node1 address> \ --join=<node1 address>,<node2 address>,<node3 address> \ --cache=.25 \ --max-sql-memory=.25 \ --backgroundThis command primes the node to start, using the following flags:
Flag Description --certs-dirSpecifies the directory where you placed the ca.crtfile and thenode.crtandnode.keyfiles for the node.--advertise-addrSpecifies 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-addrunspecified, the node listens on all IP addresses).
In some networking scenarios, you may need to use--advertise-addrand/or--listen-addrdifferently. For more details, see Networking.--joinIdentifies 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-memoryIncreases the node's cache and temporary SQL memory size to 25% of available system memory to improve read performance and increase capacity for in-memory SQL processing. For more details, see Cache and SQL Memory Size. --backgroundStarts 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
--localityas well. It is also required to use certain enterprise features. For more details, see Locality.For other flags not explicitly set, the command uses default values. For example, the node stores data in
--store=cockroach-dataand binds Admin UI HTTP requests to--http-addr=<node1 address>:8080. To set these options manually, see Start a Node.Repeat these steps for each additional node that you want in your cluster.
For each initial node of your cluster, complete the following steps:
SSH to the machine where you want the node to run. Ensure you are logged in as the
rootuser.Download the CockroachDB archive for Linux, and extract the binary:
$ curl https://binaries.cockroachdb.com/cockroach-v19.1.11.linux-amd64.tgz \ | tar -xzCopy the binary into the
PATH:$ cp -i cockroach-v19.1.11.linux-amd64/cockroach /usr/local/bin/If you get a permissions error, prefix the command with
sudo.Create the Cockroach directory:
$ mkdir /var/lib/cockroachCreate a Unix user named
cockroach:$ useradd cockroachMove the
certsdirectory to thecockroachdirectory.$ mv certs /var/lib/cockroach/Change the ownership of
Cockroachdirectory to the usercockroach:$ chown -R cockroach.cockroach /var/lib/cockroachDownload the sample configuration template and save the file in the
/etc/systemd/system/directory:$ wget -qO- https://raw.githubusercontent.com/cockroachdb/docs/master/_includes/v19.1/prod-deployment/securecockroachdb.serviceAlternatively, you can create the file yourself and copy the script into it:
[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=60 Restart=always RestartSec=10 StandardOutput=syslog StandardError=syslog SyslogIdentifier=cockroach User=cockroach [Install] WantedBy=default.targetIn the sample configuration template, specify values for the following flags:
Flag Description --advertise-addrSpecifies 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-addrunspecified, the node listens on all IP addresses).
In some networking scenarios, you may need to use--advertise-addrand/or--listen-addrdifferently. For more details, see Networking.--joinIdentifies 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
--localityas well. It is also required to use certain enterprise features. For more details, see Locality.For other flags not explicitly set, the command uses default values. For example, the node stores data in
--store=cockroach-dataand binds Admin UI HTTP requests to--http-addr=localhost:8080. To set these options manually, see Start a Node.Start the CockroachDB cluster:
$ systemctl start securecockroachdbRepeat these steps for each additional node that you want in your cluster.
systemd handles node restarts in case of node failure. To stop a node without systemd restarting it, run systemctl stop securecockroachdb
Step 4. Initialize the cluster
On your local machine, run the cockroach init command to complete the node startup process and have them join together as a cluster:
$ cockroach init --certs-dir=certs --host=<address of any node>
After running this command, each node prints helpful details to the standard output, such as the CockroachDB version, the URL for the admin UI, and the SQL URL for clients.
Step 5. Test the cluster
CockroachDB replicates and distributes data behind-the-scenes and uses a 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 built-in SQL client locally as follows:
On your local machine, launch the built-in SQL client, with the
--hostflag set to the address of the load balancer:$ cockroach sql --certs-dir=certs --host=<address of load balancer>Create a
securenodetestdatabase:> CREATE DATABASE securenodetest;View the cluster's databases, which will include
securenodetest:> SHOW DATABASES;+--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | securenodetest | | pg_catalog | | system | +--------------------+ (5 rows)Use
\qto 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.
HAProxy 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.
On your local machine, run the
cockroach gen haproxycommand with the--hostflag set to the address of any node and security flags pointing to the CA cert and the client cert and key:$ cockroach gen haproxy \ --certs-dir=certs \ --host=<address of any node>By default, the generated configuration file is called
haproxy.cfgand looks as follows, with theserveraddresses pre-populated correctly: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 8080The file is preset with the minimal configurations needed to work with your running cluster:
Field Description timeout connecttimeout clienttimeout serverTimeout values that should be suitable for most deployments. bindThe 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, as26257is likely already being used by the CockroachDB node.balanceThe balancing algorithm. This is set to roundrobinto ensure that connections get rotated amongst nodes (connection 1 on node 1, connection 2 on node 2, etc.). Check the HAProxy Configuration Manual for details about this and other balancing algorithms.option httpchkThe HTTP endpoint that HAProxy uses to check node health. /health?ready=1ensures that HAProxy doesn't direct traffic to nodes that are live but not ready to receive requests.serverFor each included node, this field specifies the address the node advertises to other nodes in the cluster, i.e., the addressed pass in the --advertise-addrflag 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.
Upload the
haproxy.cfgfile to the machine where you want to run HAProxy:$ scp haproxy.cfg <username>@<haproxy address>:~/SSH to the machine where you want to run HAProxy.
Install HAProxy:
$ apt-get install haproxyStart HAProxy, with the
-fflag pointing to thehaproxy.cfgfile:$ haproxy -f haproxy.cfgRepeat these steps for each additional instance of HAProxy you want to run.
Step 7. Run a sample workload
CockroachDB offers a pre-built workload binary for Linux that includes several load generators for simulating client traffic against your cluster. This step features CockroachDB's version of the TPC-C workload.
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
certsdirectory containingca.crt,client.root.crt, andclient.root.keyfiles.Download
workloadand make it executable:$ wget https://edge-binaries.cockroachdb.com/cockroach/workload.LATEST ; chmod 755 workload.LATESTRename and copy
workloadinto thePATH:$ cp -i workload.LATEST /usr/local/bin/workloadStart the TPC-C workload, pointing it at the IP address of the load balancer and the location of the
ca.crt,client.root.crt, andclient.root.keyfiles:$ workload run tpcc \ --drop \ --init \ --duration=20m \ --tolerate-errors \ "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"This command runs the TPC-C workload against the cluster for 20 minutes, loading 1 "warehouse" of data initially and then issuing about 12 queries per minute via 10 "worker" threads. These workers share SQL connections since individual workers are idle for long periods of time between queries.
Tip:For moretpccoptions, useworkload run tpcc --help. For details about other load generators included inworkload, useworkload run --help.To monitor the load generator's progress, open the Admin UI by pointing a browser to the address in the
adminfield in the standard output of any node on startup.For each user who should have access to the Admin UI for a secure cluster, create a user with a password and assign them to an
adminrole if necessary. On accessing the Admin UI, the users will see a Login screen, where they will need to enter their usernames and passwords.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 built-in safeguards against failure, 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 Monitoring and Alerting.
Step 9. Scale the cluster
You can start the nodes manually or automate the process using systemd.
For each additional node you want to add to the cluster, complete the following steps:
SSH to the machine where you want the node to run.
Download the CockroachDB archive for Linux, and extract the binary:
$ curl https://binaries.cockroachdb.com/cockroach-v19.1.11.linux-amd64.tgz \ | tar -xzCopy the binary into the
PATH:$ cp -i cockroach-v19.1.11.linux-amd64/cockroach /usr/local/bin/If you get a permissions error, prefix the command with
sudo.Run the
cockroach startcommand, passing the new node's address as the--advertise-addrflag and pointing--jointo the three existing nodes (also include--localityif you set it earlier).$ cockroach start \ --certs-dir=certs \ --advertise-addr=<node4 address> \ --join=<node1 address>,<node2 address>,<node3 address> \ --cache=.25 \ --max-sql-memory=.25 \ --backgroundUpdate your load balancer to recognize the new node.
For each additional node you want to add to the cluster, complete the following steps:
SSH to the machine where you want the node to run. Ensure you are logged in as the
rootuser.Download the CockroachDB archive for Linux, and extract the binary:
$ curl https://binaries.cockroachdb.com/cockroach-v19.1.11.linux-amd64.tgz \ | tar -xzCopy the binary into the
PATH:$ cp -i cockroach-v19.1.11.linux-amd64/cockroach /usr/local/bin/If you get a permissions error, prefix the command with
sudo.Create the Cockroach directory:
$ mkdir /var/lib/cockroachCreate a Unix user named
cockroach:$ useradd cockroachMove the
certsdirectory to thecockroachdirectory.$ mv certs /var/lib/cockroach/Change the ownership of
Cockroachdirectory to the usercockroach:$ chown -R cockroach.cockroach /var/lib/cockroachDownload the sample configuration template:
$ wget -qO- https://raw.githubusercontent.com/cockroachdb/docs/master/_includes/v19.1/prod-deployment/securecockroachdb.serviceAlternatively, you can create the file yourself and copy the script into it:
[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=60 Restart=always RestartSec=10 StandardOutput=syslog StandardError=syslog SyslogIdentifier=cockroach User=cockroach [Install] WantedBy=default.targetSave the file in the
/etc/systemd/system/directory.Customize the sample configuration template for your deployment:
Specify values for the following flags in the sample configuration template:
Flag Description --advertise-addrSpecifies 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-addrunspecified, the node listens on all IP addresses).
In some networking scenarios, you may need to use--advertise-addrand/or--listen-addrdifferently. For more details, see Networking.--joinIdentifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. 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:
- Implement your data model.
- Create users and grant them privileges.
- Connect your application. Be sure to connect your application to the load balancer, not to a CockroachDB node.
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 Configure Replication Zones.
Warning:When running a cluster of 5 nodes or more, it's safest to increase the replication factor for important internal data 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.
See also
On this page