大网数据广告活动
服务器运维问答

Postgresql: How to determine if database docker container running?

· 52CE 我爱测

On an docker image's entrypoint shell script I want to determine if a postgresql container can listen to connections. For mysql I used the following snippet: while ! mysqladmin ping -h"$MOODLE_DB_HOST" -P $MOODLE_DB_PORT --silent…

问题原文

原帖链接 · Dimitrios Desyllas · CC BY-SA 3.0

On an docker image's entrypoint shell script I want to determine if a postgresql container can listen to connections. For mysql I used the following snippet:

while ! mysqladmin ping -h"$MOODLE_DB_HOST" -P $MOODLE_DB_PORT --silent; do
  echo "Connecting to ${MOODLE_DB_HOST} Failed"
  sleep 1
done

How can I achieve a similar using postgresql?

已采纳解答

原帖链接 · Dimitrios Desyllas · CC BY-SA 4.0

On the dockerfile add:

RUN apt-get update && apt-get install -f -y postgresql-client

Then on the entrypoint script use:

  while ! pg_isready -h ${MOODLE_DB_HOST} -p ${MOODLE_DB_PORT} > /dev/null 2> /dev/null; do
    echo "Connecting to ${MOODLE_DB_HOST} Failed"
    sleep 1
  done

Another approach

An another approach is by using netcat:

     for count in {1..100}; do
          echo "Pinging mysql database attempt "${count}
          if  $(nc -z ${DB_HOST} ${DB_PORT}) ; then
            echo "Can connect into database"
            break
          fi
          sleep 5
    done

Where variable ${DB_HOST} contains the database host whilst ${DB_PORT} contains the database port. Thas works on most databases (except if you want to detect its type as well where a custom script is needed).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-11-29)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。