Search code examples
dockercassandra

Why am I getting a ConnectionRefusedError when running a command while trying to start my Cassandra Docker image?


I have the following docker-compose.yml file...

version: '2'

services:
  cassandra:
    image: cassandra:latest
    ports:
      - 9042:9042
    environment:
      - CASSANDRA_AUTHENTICATOR=AllowAllAuthenticator
      - CASSANDRA_AUTHORIZER=AllowAllAuthorizer
    command: >
      cqlsh -e "CREATE KEYSPACE IF NOT EXISTS cbusha
      WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}"; fi'

But now when I try to run docker-compose up I get

2024-03-22 22:16:47 Connection error: ('Unable to connect to any servers', {'127.0.0.1:9042': ConnectionRefusedError(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

What am I missing?

I can connect to it with the IJ tool so I know it is up.


Solution

  • I think that the issue here is that the Cassandra server is not ready when you try to run the cqlsh command. However, evidently by the time you access it using IJ it's ready.

    Try this setup that waits for the server to be ready.

    🗎 docker-compose.yml

    version: '2'
    
    services:
      cassandra:
        container_name: cassandra
        image: cassandra:latest
        ports:
          - 9042:9042
        environment:
          - CASSANDRA_AUTHENTICATOR=AllowAllAuthenticator
          - CASSANDRA_AUTHORIZER=AllowAllAuthorizer
        logging:
          driver: none
    
      cassandra-init:
        image: cassandra:latest
        volumes:
          - ./init-cassandra.sh:/init-cassandra.sh
        command: /bin/bash /init-cassandra.sh
        depends_on:
          - cassandra
    

    🗎 init-cassandra.sh

    #!/bin/bash
    
    until cqlsh -e "describe keyspaces" cassandra 9042 >/dev/null 2>&1; do
      echo "Waiting for Cassandra to be ready..."
      sleep 10
    done
    
    echo "Create keyspace..."
    cqlsh -e "CREATE KEYSPACE IF NOT EXISTS cbusha WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};" cassandra 9042
    echo "Done!"
    

    As you can see from the screenshot below it takes a while (roughly a minute) for the Cassandra server to become available.

    enter image description here