How to run Cassandra Container locally?

abhijithganesh

Abhijith Ganesh

Posted on October 19, 2021

How to run Cassandra Container locally?

Most of us have heard about Apache Cassandra, it is an open sourced distributed NoSQL Database which is used by large corporations like Facebook, Uber, etc

I will be explaining how to create a container with cassandra and connect into it to execute the Cassandra Query Language(CQL) statements.

Cassandra offers various advantages like:

  • Scalability
  • Maximum Fault Tolerance across NoSQL databases
  • Multi Data-Center support and Hybrid Cloud support

In this tutorial, I will be explaining how to create an instance on Docker and execute basic cqlsh commands

Basically, all docker containers can be established with a yaml, the compose file for this is

version: '3.9'

services:
  db:
    container_name: cassandra-dev
    image: cassandra
    ports:
      - 9042:9042
    environment:
      CASSANDRA_USE_ASTRA: "false" 
      CASSANDRA_USER: "cassandra" 
      CASSANDRA_PASSWORD: "cassandra" 
      CASSANDRA_LOCAL_DC: "datacenter1" 
      CASSANDRA_CONTACT_POINTS: "db:9042"
      CASSANDRA_KEYSPACE_CQL: "CREATE KEYSPACE test_keyspace WITH REPLICATION = {'class':'SimpleStrategy','replication_factor':1};" 
      MONITORING_PROMETHEUS: "false"
      MONITORING_GRAFANA: "false"
      DISTRIBUTED_TRACING_ENABLED: "false"

Enter fullscreen mode Exit fullscreen mode

Once you've created this yaml, open your CLI and run the following command, I have explained what it does down below

docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

In a nutshell, this yaml tells docker to spin up a container with the following details

  • Pull up the Cassandra Image
  • Spin it up on the container named “Cassandra-local”
  • Expose it on ports 9042
  • Create a Cassandra user with the following parameters
  • username: Cassandra, password: Cassandra
  • Create a keyspace (similar to database if you’re from a SQL background) , called test_keyspace To access the database/keyspace you can access the shell by using the following command
>docker exec -it cassandra-dev /bin/bash
>cqlsh
Enter fullscreen mode Exit fullscreen mode

To create a keyspace use the following commands:

    CREATE KEYSPACE test_keyspace_2;
    USE test_keyspace_2;
    CREATE TABLE IF NOT EXISTS test_table(
      id         uuid,
      first_name text,
      last_name  text,
      address    text,
      city       text,
      telephone  text,
      PRIMARY KEY ((id))
    );
Enter fullscreen mode Exit fullscreen mode

You can consider using the DDL and DML commands from the docs here

The connection to docker has been successful and now you can connect it to learn CQL.

💖 💪 🙅 🚩
abhijithganesh
Abhijith Ganesh

Posted on October 19, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related