如何在docker compose多容器应用程序中使用gocql连接到bitnami/cassandra?

zz2j4svz  于 2021-06-09  发布在  Cassandra
关注(0)|答案(1)|浏览(340)

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

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 尝试使用创建cassandra会话 gocql :

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

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

bjg7j2ky

bjg7j2ky1#

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

相关问题