Skip to content

Instantly share code, notes, and snippets.

@nclavaud
Last active January 25, 2021 08:18
Show Gist options
  • Save nclavaud/48c0a2f1562ee880549341fc41006b2f to your computer and use it in GitHub Desktop.
Save nclavaud/48c0a2f1562ee880549341fc41006b2f to your computer and use it in GitHub Desktop.
PostgreSQL, quick!
#!/bin/sh
# PostgreSQL, quick!
DOCKER_NETWORK="dev"
PG_HOST="pg"
PG_PASSWORD="pgrocks!"
# 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
fi
# 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
fi
# 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;
fi
# 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
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment