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

701 Views Asked by At

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 !

2

There are 2 best solutions below

3
Alex Ott On BEST ANSWER

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)

0
Mohsan Abbas On

If both containers using bridge network you need to specify the network name in both containers and in your app container the host will be cassandra (docker) container.

services:
  cassandra:
    image: cassandra:4.0
    container_name: cassandra
    
    ports:
      - 9042:9042

    volumes:
      - ~/apps/cassandra:/var/lib/cassandra

    networks:
      - default
    environment:
      - CASSANDRA_CLUSTER_NAME=mycluster

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

    environment:
      - HOSTS=cassandra
      ...

networks:
  default:
    driver: bridge