Introduction
CockroachDB is a distributed SQL database designed for resilience and horizontal scalability, with 100% PostgreSQL compatibility. Unlike traditional databases like MySQL that struggle to scale, CockroachDB spreads data across multiple nodes with no single point of failure—like a swarm of bees where any bee can take over.
In 2026, with the rise of cloud-native apps and microservices, it's essential for developers building geo-distributed databases with high availability. This beginner tutorial takes you from local Docker installation to connecting a Node.js app, including hands-on SQL queries. By the end, you'll have a production-ready setup in insecure mode for testing. Key benefits: zero downtime during traffic spikes and queries that survive node crashes. Ready to dive into distributed databases? (128 words)
Prerequisites
- Docker installed and running (version 20+).
- Basic SQL knowledge (SELECT, INSERT).
- Node.js 18+ for the app example (optional).
- Unix-like terminal (WSL on Windows).
- 2 GB free RAM for the container.
Installing CockroachDB with Docker
docker run -d \
--name=cockroachdb \
-p 26257:26257 \
-p 8080:8080 \
-v $(pwd)/cockroach-data:/cockroach/cockroach-data \
cockroachdb/cockroach:v24.1.0 start-single-node \
--insecure \
--listen-addr=0.0.0.0This script starts a single-node CockroachDB instance in insecure mode (dev only) on ports 26257 (SQL) and 8080 (UI). The volume persists data locally. Avoid --insecure in production; use certificates instead. Check with docker ps to confirm the container is running.
Accessing the Web UI and Verification
Open http://localhost:8080 in your browser. You'll see the CockroachDB dashboard with real-time metrics: CPU, storage, queries/sec. Click Explore to view system tables.
If the container doesn't start, check the logs: docker logs cockroachdb. Think of it like an airplane cockpit—everything is monitored. Next step: SQL shell.
Connecting to the Interactive SQL Shell
docker exec -it cockroachdb \
./cockroach sql \
--insecure \
-e "SHOW DATABASES;"This runs the cockroach sql shell inside the container to list system databases (defaultdb, information_schema, etc.). The -e option executes a single command. For an interactive shell, omit -e. Exit with \q. Pitfall: certificates required without --insecure.
Creating the Database, Table, and User
CREATE DATABASE bank;
USE bank;
CREATE TABLE accounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
balance INT NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT now()
);
CREATE USER maxroach PASSWORD 'testpass';
GRANT ALL ON DATABASE bank TO maxroach;
GRANT ALL ON TABLE accounts TO maxroach;This script creates a bank database, an accounts table with auto-generated UUID (ideal for distributed setups), and a maxroach user. Run it with docker exec -it cockroachdb ./cockroach sql --insecure < setup.sql. Why UUID? Prevents conflicts during sharding. Verify with SHOW TABLES;. Don't forget GRANT for app access.
Inserting and Reading Data
Test your inserts: Imagine a bank where balances update in real-time across multiple data centers. Run the following queries in the shell to populate the table.
Inserting and Querying Data
USE bank;
INSERT INTO accounts (balance) VALUES (1000), (2500);
SELECT id, balance, created_at FROM accounts;
UPDATE accounts SET balance = balance + 500 WHERE id = (SELECT id FROM accounts LIMIT 1);
SELECT SUM(balance) FROM accounts;This inserts 2 accounts, reads everything, updates the first one (+500), and sums the balances. Expected result: 2 initial rows, then total 4000. CockroachDB handles distributed ACID transactions. Note: no RETURNING here, but it's available like in Postgres.
Connecting from a Node.js App
To integrate with code, we'll use the pg client (Postgres-compatible). Create a node-app folder and initialize npm.
Node.js Setup and Full Script Installation
mkdir node-app && cd node-app
npm init -y
npm install pg
npm install -g ts-node typescript @types/pgThis initializes a Node project with pg for connections. TypeScript is optional for type safety. Run the following TS script next. Ports open: 26257 for TCP SQL.
Node.js App Connected to CockroachDB
import { Client } from 'pg';
const client = new Client({
host: 'localhost',
port: 26257,
database: 'bank',
user: 'maxroach',
password: 'testpass',
ssl: false,
});
async function main() {
await client.connect();
console.log('Connecté à CockroachDB !');
const res = await client.query('SELECT * FROM accounts');
console.log('Comptes:', res.rows);
await client.query('INSERT INTO accounts (balance) VALUES ($1)', [999]);
console.log('Nouveau compte ajouté');
await client.end();
}
main().catch(console.error);This complete TS script connects, queries the table, and inserts an account. Run with ts-node app.ts. ssl: false for insecure mode. In production, enable SSL and use connection pooling. Check logs: account list + new UUID.
Best Practices
- Always use UUID or SERIAL for PK: Avoids collisions during multi-node scaling.
- Enable security: Replace
--insecurewith--certs-dirin production. - Monitor via UI: Check /#/metrics for hotspots.
- Automated backups: Use
BACKUP INTO 's3://...'for resilience. - Connection pooling: Use
pg-poolfor >100 concurrent connections.
Common Errors to Avoid
- Port 26257 blocked: Check firewall;
docker runexposes it explicitly. - Insecure mode in prod: Vulnerable to attacks; generate certs with
cockroach cert. - Forgot Docker volume: Data lost on restart; always mount
-v. - Long transactions: Distributed timeouts; batch inserts (>1000 rows slow things down).
Next Steps
- Official docs: CockroachDB Quickstart.
- Multi-node cluster tutorial: Deploy multi-node.
- Kubernetes: CockroachDB Helm chart.
- Check our Learni courses on distributed databases to master Yugabyte or TiDB.