猿问

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

我正在尝试构建一个使用用户名和密码身份验证连接到 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

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


萧十郎
浏览 154回答 1
1回答

UYOU

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 refusedbackend_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 refusedbackend_1    | 2020/11/04 17:53:37 Connected OK
随时随地看视频慕课网APP

相关分类

Go
我要回答