为什么我在尝试启动 Cassandra Docker 映像时运行命令时收到 ConnectionRefusedError?

问题描述 投票:0回答:1

我有以下

docker-compose.yml
文件...

version: '2'

services:
  cassandra:
    image: cassandra:latest
    ports:
      - 9042:9042
    environment:
      - CASSANDRA_AUTHENTICATOR=AllowAllAuthenticator
      - CASSANDRA_AUTHORIZER=AllowAllAuthorizer
    command: >
      cqlsh -e "CREATE KEYSPACE IF NOT EXISTS cbusha
      WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}"; fi'

但是现在当我尝试跑步时

docker-compose up
我明白了

2024-03-22 22:16:47 Connection error: ('Unable to connect to any servers', {'127.0.0.1:9042': ConnectionRefusedError(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

我错过了什么?

我可以使用 IJ 工具连接到它,所以我知道它已经启动。

docker cassandra
1个回答
0
投票

我认为这里的问题是当您尝试运行

cqlsh
命令时 Cassandra 服务器尚未准备好。然而,显然当您使用 IJ 访问它时,它已经准备好了。

尝试此设置,等待服务器准备就绪。

🗎

docker-compose.yml

version: '2'

services:
  cassandra:
    container_name: cassandra
    image: cassandra:latest
    ports:
      - 9042:9042
    environment:
      - CASSANDRA_AUTHENTICATOR=AllowAllAuthenticator
      - CASSANDRA_AUTHORIZER=AllowAllAuthorizer
    logging:
      driver: none

  cassandra-init:
    image: cassandra:latest
    volumes:
      - ./init-cassandra.sh:/init-cassandra.sh
    command: /bin/bash /init-cassandra.sh
    depends_on:
      - cassandra

🗎

init-cassandra.sh

#!/bin/bash

until cqlsh -e "describe keyspaces" cassandra 9042 >/dev/null 2>&1; do
  echo "Waiting for Cassandra to be ready..."
  sleep 10
done

echo "Create keyspace..."
cqlsh -e "CREATE KEYSPACE IF NOT EXISTS cbusha WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};" cassandra 9042
echo "Done!"

从下面的屏幕截图中可以看到,Cassandra 服务器需要一段时间(大约一分钟)才能可用。

© www.soinside.com 2019 - 2024. All rights reserved.