初始化容器等待 rabbit-mq 就绪

Init container to wait for rabbit-mq readiness

我在 docker-library/healthcheck 看到了 docker RabbitMQ 健康检查的例子。

我想对我的 Kubernetes 部署应用类似的机制以等待 Rabbit 部署准备就绪。我正在对 MongoDB 做类似的事情,使用一个容器,该容器使用一些 ping 命令忙等待 mongo。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-1
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app-1
  template:
    metadata:
      labels:
        app: app-1
    spec:
      initContainers:
        - name: wait-for-mongo
          image: gcr.io/app-1/tools/mongo-ping
      containers:
        - name: app-1-service
          image: gcr.io/app-1/service
          ...

然而,当我试图构建这样一个初始化容器时,我找不到任何关于如何从集群外部查询 rabbit 健康状况的解决方案。

根据@Hanx 的建议改编自此example

Docker 文件

FROM python:3-alpine

ENV RABBIT_HOST="my-rabbit"
ENV RABBIT_VHOST="vhost"
ENV RABBIT_USERNAME="root"

RUN pip install pika

COPY check_rabbitmq_connection.py /check_rabbitmq_connection.py
RUN chmod +x /check_rabbitmq_connection.py

CMD ["sh", "-c", "python /check_rabbitmq_connection.py --host $RABBIT_HOST --username $RABBIT_USERNAME --password $RABBIT_PASSWORD --virtual_host $RABBIT_VHOST"]

check_rabbitmq_connection.py

#!/usr/bin/env python3
# Check connection to the RabbitMQ server
# Source: https://blog.sleeplessbeastie.eu/2017/07/10/how-to-check-connection-to-the-rabbitmq-message-broker/

import argparse
import time
import pika

# define and parse command-line options
parser = argparse.ArgumentParser(description='Check connection to RabbitMQ server')
parser.add_argument('--host', required=True, help='Define RabbitMQ server hostname')
parser.add_argument('--virtual_host', default='/', help='Define virtual host')
parser.add_argument('--port', type=int, default=5672, help='Define port (default: %(default)s)')
parser.add_argument('--username', default='guest', help='Define username (default: %(default)s)')
parser.add_argument('--password', default='guest', help='Define password (default: %(default)s)')
args = vars(parser.parse_args())

print(args)

# set amqp credentials
credentials = pika.PlainCredentials(args['username'], args['password'])
# set amqp connection parameters
parameters = pika.ConnectionParameters(host=args['host'], port=args['port'], virtual_host=args['virtual_host'], credentials=credentials)

# try to establish connection and check its status
while True:
    try:
        connection = pika.BlockingConnection(parameters)
        if connection.is_open:
            print('OK')
            connection.close()
            exit(0)
    except Exception as error:
        raise
        print('No connection yet:', error.__class__.__name__)
        time.sleep(5)

构建并 运行:

docker build -t rabbit-ping .

docker run --rm -it \
    --name rabbit-ping \
    --net=my-net \
    -e RABBIT_PASSWORD="<rabbit password>" \
    rabbit-ping

并在 deployment.yaml 中:

apiVersion: apps/v1
kind: Deployment
...
spec:
  ...
  template:
    ...
    spec:
      initContainers:
        - name: wait-for-rabbit
          image: gcr.io/my-org/rabbit-ping
          env:
            - name: RABBIT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: rabbit
                  key: rabbit-password
      containers:
        ...

以下工作没有任何额外的 images/scripts,但需要您启用 Management Plugin,例如使用 rabbitmq:3.8-management 图像而不是 rabbitmq:3.8

initContainers:
  - name: check-rabbitmq-ready
    image: busybox
    command: [ 'sh', '-c',
        'until wget http://guest:guest@rabbitmq:15672/api/aliveness-test/%2F;
        do echo waiting for rabbitmq; sleep 2; done;' ]

具体来说,这是等待 HTTP 管理 API 可用,然后检查默认 vhost 是否正常 运行。 %2F 指的是默认的 / vhost,必须对其进行 urlendoded。如果使用您自己的虚拟主机,请改为输入。