How to Use CockroachDB: A Complete Tutorial
Introduction
If you need a highly scalable and resilient SQL database for distributed environments, CockroachDB (Official site) is an excellent choice. It is designed to provide strong consistency, high availability, and easy horizontal scaling. This tutorial will guide you through the basics of using CockroachDB from installation through to performing everyday database operations and troubleshooting.
Prerequisites
- A system running Linux, macOS, or Windows with access to command line tools.
- Basic SQL knowledge.
- Administrator or sudo privileges for installation.
- Internet connection to download binaries or use Docker images.
Step 1: Installing CockroachDB
You can install CockroachDB through multiple methods: downloading binaries, using Docker, or via package managers depending on your OS.
- To download prebuilt binaries, visit CockroachDB docs (official).
- For Docker users, run:
docker pull cockroachdb/cockroach - For Linux package managers or macOS Homebrew, follow instructions in the official docs.
Step 2: Starting a Local Cluster
CockroachDB runs as a distributed cluster, even on a single machine for development.
cockroach start --insecure --listen-addr=localhost:26257 --http-addr=localhost:8080 --store=cs1 --background
This command starts a single-node insecure cluster for local development listening on port 26257 for SQL and 8080 for the web console.
Step 3: Access the SQL Client
Run the Cockroach SQL client to interact with the database:
cockroach sql --insecure --host=localhost:26257
Step 4: Basic Database Operations
Inside the SQL shell, try creating a database and table, inserting data, and running queries:
CREATE DATABASE example_db;
USE example_db;
CREATE TABLE users (id INT PRIMARY KEY, name STRING, email STRING);
INSERT INTO users VALUES (1, 'Alice', '[email protected]');
SELECT * FROM users;
Step 5: Cluster Management
- To add more nodes, start CockroachDB on other machines (or locally with different –store and –port values) and join them to the cluster.
- Monitor your cluster from the built-in web UI at
http://localhost:8080.
Troubleshooting and Tips
- If the SQL shell cannot connect, check that your node is running and ports aren’t blocked.
- Use the
cockroach quit --host=localhost:26257command to safely stop nodes. - For production, run with secure certificates instead of –insecure.
- Back up your data regularly using CockroachDB’s built-in backup commands.
Summary Checklist
- Install CockroachDB appropriate for your system.
- Start a local or distributed cluster.
- Use the SQL client to create databases and manage data.
- Monitor and manage your cluster nodes.
- Follow best practices for security & backups in production.
Learn more about advanced features and production setups in the official CockroachDB documentation.
For related tutorials on databases, check our guide on how to install TiDB database and how to install Vitess database.
