[Postgres Bash] Wait for database

Server wait for database get ready

# From https://docs.docker.com/compose/startup-order/
#!/bin/sh
# wait-for-postgres.sh

set -e
  
host="$1"

shift
  
# Login for user (`-U`) and once logged in execute quit ( `-c \q` )
# If we can not login sleep for 1 sec
until PGPASSWORD=<password> psql -h "$host" -U "<username>" -d <database> -c '\q'; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done
  
>&2 echo "Postgres is up - executing command"
# Print and execute all other arguments starting with `$1`
exec "$@"

This is a shell script written in /bin/sh syntax. The script is designed to wait for a PostgreSQL database to become available before executing a specified command. The script takes two arguments: the hostname of the database server and the command to be executed.

The script sets an exit on error flag with set -e. It then assigns the hostname argument to the host variable and discards the first argument with shift.

The script enters a loop with until that tries to connect to the PostgreSQL server using psql with a specific username, database name, and password. The -c '\q' option is used to exit immediately after connecting to the database. The loop will repeat until a successful connection is made, and sleep for one second between each iteration.

When a successful connection is made, the script prints a message and uses the exec command to execute the remaining arguments as a separate process.

 

Client wait for server get ready:


#!/bin/sh

set -e

until curl --silent -X GET http://server:3001/api/health ; do
  echo "Waiting server container ready"
  sleep 1
done

exec "$@"

 

posted @   Zhentiw  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-02-05 [RxJS] sample
2020-02-05 [Angular] Define a custom Material theme
2019-02-05 [Functional Programming ADT] Create State ADT Based Reducers (applyTo, Maybe)
2018-02-05 [Javascirpt] Developer-friendly Flow Charts with flowchart.js
2018-02-05 [TS] Class Properties Public, Private and Read Only Modifiers
2018-02-05 [Python + Unit Testing] Write Your First Python Unit Test with pytest
2018-02-05 [React] React.PureComponent
点击右上角即可分享
微信分享提示