Postgresql: How to determine if database docker container running?
10,920
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).
Related videos on Youtube
Author by
Dimitrios Desyllas
Updated on September 18, 2022Comments
-
Dimitrios Desyllas over 1 year
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?
-
Diego Jancic over 6 yearsI've tried the same on the Alpine image using
apk add --no-cache postgresql-client
and thepg_isready
utility is not installed. Any ideas? -
Dimitrios Desyllas over 6 yearsHow about using netcat?
-
Diego Jancic over 6 yearsThanks. I might end up using either this solution: stackoverflow.com/a/17309493/72350 or this one: github.com/vishnubob/wait-for-it that internally uses netcat. Both worked.
-
Mark about 3 years@diego-jancic, I just ran
apk --update add postgresql-client
on an Alpine image, and it installed thepg_isready
utility successfully. Maybe this has changed since your comment, but, as of today, this seems to work.