首页 > 其他分享 >[Postgres Bash] Wait for database

[Postgres Bash] Wait for database

时间:2023-02-05 00:44:43浏览次数:54  
标签:Postgres script database server sleep Bash wait

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 "$@"

 

标签:Postgres,script,database,server,sleep,Bash,wait
From: https://www.cnblogs.com/Answer1215/p/17092720.html

相关文章