Skip to content

Instantly share code, notes, and snippets.

@roamingthings
Created July 21, 2016 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roamingthings/a96a88de51985044bf659112a52f8e71 to your computer and use it in GitHub Desktop.
Save roamingthings/a96a88de51985044bf659112a52f8e71 to your computer and use it in GitHub Desktop.
This script creates a Docker container running a PostgreSQL database. The data is stored on the host so it survives container re-creation. Finally `pgsql` client is executed and connects to the created container (mostly for demonstration purpose).
#! /bin/bash
# Author: Alexander Sparkowsky
# Email: info@roamingthings.de
# License: MIT
# Usage: ./init_postgres.sh _project_name_ _db_password_ _[host_path_db_data]_ _[pg_docker_image_name]_
PROJECT_NAME=$1
DB_NAME="$PROJECT_NAME"
HOST_PATH_DB_DATA=${3:-"/tmp/postgres/data/$DB_NAME"}
PG_DOCKER_IMAGE_NAME=${4:-"postgres"}
DB_CONTAINER_NAME="$PROJECT_NAME-postgres"
DB_USER="postgres"
DB_PASSWORD=$2
#
# Create data directory if not existing
#
if [ ! -x "$HOST_PATH_DB_DATA" ]; then
mkdir -p "$HOST_PATH_DB_DATA"
fi
#
# Check if container exists and is running
#
RUNNING=$(docker inspect --format="{{ .State.Running }}" $DB_CONTAINER_NAME 2> /dev/null)
if [ $? -eq 1 ]; then
# Create and run container
echo "Container does not exist"
echo "Creating new postgres container named $DB_CONTAINER_NAME"
docker run --name $DB_CONTAINER_NAME -v $HOST_PATH_DB_DATA:/var/lib/postgresql/data_on_host -e POSTGRES_PASSWORD=$DB_PASSWORD -e PGDATA=/var/lib/postgresql/data_on_host -d $PG_DOCKER_IMAGE_NAME
fi
if [ "$RUNNING" == "false" ]; then
# Start container
echo "Starting existing container"
docker start $DB_CONTAINER_NAME
fi
#
# Wait for container to start up
#
echo "Giving postgres some time to start up..."
sleep 7
# Execute pgsql and connect to container
docker run -it --rm --link $DB_CONTAINER_NAME:postgres $PG_DOCKER_IMAGE_NAME psql -h postgres -U $DB_USER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment