Easy Connecting Cassandra in Docker with NodeJS

Reference: https://hub.docker.com/_/cassandra

Pull and Run Cassandra in Docker

This will connect local port to docker container port on 7000, 7001, 7199, 9042, and 9160, which are the Cassandra default ports. The –name specifies name of docker container, and pulling -d the cassandra:latest image.

docker run --name cassandra-container -p 7000:7000 -p 7001:7001 -p 7199:7199 -p 9042:9042 -p 9160:9160 -d cassandra:latest

Try connecting Cassandra in Terminal

After creating Cassandra in Docker, we use cqlsh to directly connect to Cassandra. You may also use bash to connect to container first, then enter “cqlsh” to connect to database.

docker exec -it cassandra cqlsh

Create a KEYSPACE

In cqlsh>, we could see KEYSPACES by typing in “DESC KEYSPACES”. The default ones are “system / system_distributed / system_traces / system_virtual_schema / system_auth / system_schema / system_views.

Before creating, “Cluster” is an entire database system, containing “Datacenter”, which will consists of multiple “Node”. Nodes are responsible for storing and managing a subset of the data in the database. In it, we store our “KEYSPACE”, which will consists of multiple “TABLE”.

The replication class depends on Data Centers, if you have multiple, use “NetworkTopologyStrategy” instead. It allows you to specify different replication factors for each data center. And replication_factor let you set different replication factors for each data center.

CREATE KEYSPACE mykeyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};

Connecting using Node.js

Following by Node.js connection testing, we create a Node.js env and use the following script to test if Node.js could connect.

// db_connection_test.js
import cassandra from 'cassandra-driver';

// Set up the Cassandra Client
const client = new cassandra.Client({
    contactPoints: ['127.0.0.1'], // ip address of the cassandra cluster
    localDataCenter: 'datacenter1', // data center of the cassandra cluster
    keyspace: 'mykeyspace' // keyspace of the cassandra cluster
});

// Connect to Cassandra
client.connect()
    .then(() => {
        console.log('Connected to Cassandra');
    })
    .catch((error) => {
        console.error('Error connecting to Cassandra', error);
    });

Next, In terminal:

node db_connection_test.js
// Connected to Cassandra

Then we could start our journey using Cassandra as our database!