Skip to content

Instantly share code, notes, and snippets.

Last active January 25, 2021 08:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
PostgreSQL, quick!
# PostgreSQL, quick!
# pull docker image
docker image inspect postgres > /dev/null || docker pull postgres
# check if network exists already
docker network ls --format '{{.Name}}' | grep "^${DOCKER_NETWORK}$" > /dev/null
if [ "$?" -eq 1 ]; then
# create a docker network
echo "Create docker network"
docker network create ${DOCKER_NETWORK} > /dev/null 2>&1
# check if a running container exists already
docker ps --format '{{.Names}}' | grep "^${PG_HOST}$" > /dev/null
if [ "$?" -eq 1 ]; then
# create a server
echo "Create PostgreSQL server"
docker run --rm -it --name ${PG_HOST} --network dev -e POSTGRES_PASSWORD=${PG_PASSWORD} -d postgres > /dev/null
# output container network info
ip=`docker inspect ${PG_HOST} -f "{{.NetworkSettings.Networks.${DOCKER_NETWORK}.IPAddress}}"`
port=`docker inspect ${PG_HOST} -f '{{.Config.ExposedPorts}}' | grep -oE '[0-9]+'`
echo "Server running at ${ip} on port ${port}"
# stop here if no connection required
if [ "$1" = "--no-connect" ]; then
exit 0;
# create a client and connect (with retry)
echo "Connect with PostgreSQL client"
for i in 1 2 3 4 5; do
docker run -it --rm --network ${DOCKER_NETWORK} -v $PWD:/var/local -e PGPASSWORD=${PG_PASSWORD} postgres psql -h ${PG_HOST} -U postgres \
&& break
echo "Retrying in $i second(s)"
sleep $i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment