Golang with Cassandra db using docker-compose : cannot connect (gocql)

Issue

I am trying to setup a cassandra DB and connect to it with a golang app.

this is my docker-compose


version: "3.6"

services:
  cassandra:
    image: cassandra:4.0
    ports:
      - 9042:9042
    volumes:
      - ~/apps/cassandra:/var/lib/cassandra
    environment:
      - CASSANDRA_CLUSTER_NAME=mycluster

  myapp:
    ...
    ports:
      - 4242:4242
      - 4243:4243
    depends_on:
      - cassandra
      ...

networks:
  default:
    driver: bridge

I start the Cassandra using

docker-compose up cassandra

and then I wait it to be ready.

Then I try to connect to Cassandra in local using

> cqlsh
Connected to mycluster at 127.0.0.1:9042

and then I try to connect to it in my go app (dockerized) using gocql

    cluster := gocql.NewCluster("127.0.0.1")
    session, err := cluster.CreateSession()

( also tried to add element as Consistency, ProtoVersion=4 etc. same results)

it says then :

Cannot connect to db: gocql: unable to create session: unable to discover protocol version: dial tcp 127.0.0.1:9042: connect: connection refused

Do you. have any idea why it can’t connect?

thanks !

Solution

Each container has its own localhost (127.0.0.1) address – you need to connect to IP address of your machine (if you use bridge), or maybe better to connect by the name (cassandra)

Answered By – Alex Ott

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.