如何在 Docker Compose 多容器应用程序中使用 GoCQL 连接到 bitnami/cassandra?

How to connect to bitnami/cassandra using GoCQL in a Docker Compose multi-container application?

我正在尝试构建一个使用用户名和密码身份验证连接到 Cassandra 的应用程序的简化示例。为此,我将 https://hub.docker.com/r/bitnami/cassandra/ 中的 docker-compose.yml 改编如下:

version: '2'

services:
  cassandra:
    image: 'docker.io/bitnami/cassandra:3-debian-10'
    ports:
      - '7000:7000'
      - '9042:9042'
    volumes:
      - 'cassandra_data:/bitnami'
    environment:
      - CASSANDRA_SEEDS=cassandra
      - CASSANDRA_PASSWORD_SEEDER=yes
      - CASSANDRA_PASSWORD=cassandra
  backend:
    build: .
    environment:
      - CASSANDRA_USERNAME=cassandra
      - CASSANDRA_PASSWORD=cassandra
volumes:
  cassandra_data:
    driver: local

我的目录结构在哪里

.
├── Dockerfile
├── docker-compose.yml
├── go.mod
├── go.sum
└── main.go

多级Dockerfile

FROM golang AS builder
WORKDIR /go/src/app/
COPY . .
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/app/app .
CMD ["./app"]  

main.go 尝试使用 gocql:

创建 Cassandra 会话
package main

import (
    "log"
    "os"

    "github.com/gocql/gocql"
)

func main() {
    cluster := gocql.NewCluster("cassandra")
    cluster.Authenticator = gocql.PasswordAuthenticator{
        Username: os.Getenv("CASSANDRA_USERNAME"),
        Password: os.Getenv("CASSANDRA_PASSWORD"),
    }

    if _, err := cluster.CreateSession(); err != nil {
        log.Fatalf("CreateSession: %v", err)
    }
}

用户名和密码都已设置为默认值“cassandra”,如 https://hub.docker.com/r/bitnami/cassandra/ 中的“连接到其他容器”示例。

问题是,如果我尝试使用 docker-compose build 后跟 docker-compose up 运行 这个多容器应用程序,我会收到以下错误:

backend_1    | 2020/11/04 15:10:34 CreateSession: gocql: unable to create session: unable to discover protocol version: dial tcp 172.18.0.3:9042: connect: connection refused

我不明白这里出了什么问题:主机名、端口号、用户名和密码似乎都是正确的。知道为什么连接被拒绝吗?

Cassandra 需要几秒钟才能启动并开始接受连接; backend 在准备就绪之前正在尝试连接。如果您在一小段延迟后启动 backend(使用 docker-compose start backend),您的配置(对我而言)工作正常。修改 backend 以重试连接对我来说很可靠,即

for {
    _, err := cluster.CreateSession()
    if  err == nil {
        break
    }
    log.Printf("CreateSession: %v", err)
    time.Sleep(time.Second)
}
log.Printf("Connected OK")

日志:

backend_1    | 2020/11/04 17:53:23 CreateSession: gocql: unable to create session: unable to discover protocol version: dial tcp 172.26.0.2:9042: connect: connection refused
backend_1    | 2020/11/04 17:53:24 CreateSession: gocql: unable to create session: unable to discover protocol version: dial tcp 172.26.0.2:9042: connect: connection refused
.......
backend_1    | 2020/11/04 17:53:36 CreateSession: gocql: unable to create session: unable to discover protocol version: dial tcp 172.26.0.2:9042: connect: connection refused
backend_1    | 2020/11/04 17:53:37 Connected OK