Create keyspace automatically inside docker container with cassandra Create keyspace automatically inside docker container with cassandra docker docker

Create keyspace automatically inside docker container with cassandra


Base on answers from @jan-oudrincky and @alexander-morozov, I build a new docker image which has a wrapper of original docker-entrypoint.sh to create keyspace when environment variable CASSANDRA_KEYSPACE is set. It will be useful in dev/test environment.

It doesn't modify docker-entrypoint.sh so even if cassandra base image has any modification you just need a rebuild.

Dockerfile

FROM cassandraCOPY entrypoint-wrap.sh /entrypoint-wrap.shENTRYPOINT ["/entrypoint-wrap.sh"]CMD ["cassandra", "-f"]

entrypoint-wrap.sh

#!/bin/bashif [[ ! -z "$CASSANDRA_KEYSPACE" && $1 = 'cassandra' ]]; then  # Create default keyspace for single node cluster  CQL="CREATE KEYSPACE $CASSANDRA_KEYSPACE WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1};"  until echo $CQL | cqlsh; do    echo "cqlsh: Cassandra is unavailable - retry later"    sleep 2  done &fiexec /docker-entrypoint.sh "$@"


Tackled this issue today. Build image, which overwrites default Cassandra docker-entrypoint.sh with one modified, appended, right before exec "$@"

for f in docker-entrypoint-initdb.d/*; do    case "$f" in        *.sh)     echo "$0: running $f"; . "$f" ;;        *.cql)    echo "$0: running $f" && until cqlsh -f "$f"; do >&2 echo "Cassandra is unavailable - sleeping"; sleep 2; done & ;;        *)        echo "$0: ignoring $f" ;;    esac    echodone

Put the desired *.cql in image in docker-entrypoint-initdb.d/.

Image will start, boot up the cassandra, and retries inserting to the database unless it succeeds. Just make sure your scripts are IF NOT EXISTS otherwise the script will run indefinitely.


I'm using a Spring-Boot docker container to access my cassandra container. Everything is orchestrated by a dockr-compose. this tutorial in combination with the following code worked for me.

@Overrideprotected List<CreateKeyspaceSpecification> getKeyspaceCreations() {    CreateKeyspaceSpecification specification = CreateKeyspaceSpecification.createKeyspace(KEYSPACE);    return Arrays.asList(specification);}