zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

[Postgres Bash] Wait for database

Database for Bash WAIT Postgres
2023-09-14 08:59:11 时间

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