Docker - 检查postgres是否准备就绪

时间:2017-10-01 20:26:56

标签: postgresql docker centos kong

我有一个Kong API Gateway容器和一个postgres容器,我需要在运行迁移之前检查postgres是否已从Kong容器启动并准备就绪。我正在考虑使用我的Dockerfile中的RUN yum install postgresql -y && yum clean all并使用psqlpg_isready来实现此功能,将postgres客户端实用程序安装到基于官方Kong映像的自定义映像中。我创建了一个名为polling的postgres用户,其中包含一个空密码,专门用于通过这两个实用程序检查服务器的状态。它们都不起作用。

我尝试从自定义Kong图像执行这些命令:

  1. PSQL 即可。命令psql -h postgres -U polling -w -c '\l'失败,错误为psql: fe_sendauth: no password supplied。但是用户没有密码。我究竟做错了什么?使用psql检查服务器是否就绪的完整shell脚本描述为here

  2. pg_isready 即可。我不知道如何将此实用程序单独安装到基于官方Kong图像的自定义图像中,而HK图像又基于centos:7图像,postgresql包不包含pg_isready 。只安装了这些实用程序,可以在/usr/binpg_configpg_dumppg_dumpallpg_restorepsql中找到这些实用程序。如何安装pg_isready?我不想在Kong图像中安装完整的服务器。

4 个答案:

答案 0 :(得分:11)

这是使用PostgreSQL提供的pg_isready工具的一壳式班轮。

要在docker外部呼叫:

timeout 90s bash -c 'until docker exec $YOUR_DOCKER_CONTAINER_NAME pg_isready ; do sleep 5 ; done'

Based on a post from Jeroma Belleman

答案 1 :(得分:4)

我们通过端口5432上的简单TCP检查解决了这个问题,没有任何PG工具。我们只使用wait-for-it.sh,效果很好。在服务器实际准备好服务之前,Postgres不会打开端口,所以这显然很好。

示例Dockerfile:https://github.com/apim-haufe-io/wicked.kong/blob/master/Dockerfile

相应的启动脚本(此特定问题仅对最后一行感兴趣):https://github.com/apim-haufe-io/wicked.kong/blob/master/startup.sh

段:

wait-for-it.sh -h $KONG_PG_HOST -p 5432 -t 30 -- kong start --run-migrations

等待它:https://github.com/vishnubob/wait-for-it

答案 2 :(得分:2)

我的解决方案是根据官方kong图像创建一个新图像并覆盖这样的入口点:

#!/usr/bin/env bash
set -e

# Disabling nginx daemon mode
export KONG_NGINX_DAEMON="off"

# Setting default prefix (override any existing variable)
export KONG_PREFIX="/usr/local/kong"

# Prepare Kong prefix
if [ "$1" = "/usr/local/openresty/nginx/sbin/nginx" ]; then
    kong prepare -p "/usr/local/kong"
fi

#waiting for postgres
until psql --host=$KONG_PG_HOST --username=$POLLING_USER $POLLING_DATABASE -w &>/dev/null
do
  echo "Waiting for PostgreSQL..."
  sleep 1
done

echo "Postgres is ready, running the migrations..."

kong migrations up

echo "READY TO START UP KONG USING CMD" $@;

exec "$@"

答案 3 :(得分:1)

我尝试了wait-for-it,但是在docker容器中运行它可能是一个问题,因为可能没有在nc中安装docker映像(有时甚至没有ping,telnet,curl ..)。因此,要检查数据库是否正常运行,我在docker compose文件中使用了HealthCheck来检查pg_isready的返回值,postgres数据库的内容是什么,因此您无需在docker映像中安装任何内容:

version: '2.3'
services:
  postgres-db:
    image: postgresImage
    healthcheck:
      test: /usr/bin/pg_isready
      interval: 5s
      timeout: 10s
      retries: 120
    ports:
      - '5432:5432'

  aplication:
    image: applicationImage
    depends_on:
      postgres-db:
        condition: service_healthy
相关问题