6

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 !

F4Ke
  • 1,631
  • 1
  • 20
  • 49

2 Answers2

3

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)

Alex Ott
  • 80,552
  • 8
  • 87
  • 132
  • I'm not very fluent with docker-compose, how can I do that ? – F4Ke Mar 08 '22 at 17:31
  • 1
    In your app, you have to specify `cassandra` instead of `127.0.0.1`. As your app and Cassandra run in different containers, you can't use the localhost address, they are on the "different" hosts. – Hades Architect Mar 08 '22 at 22:42
  • oh, yes i see it's working like that, thanks! – F4Ke Mar 09 '22 at 08:42
0

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