Skip to content

Instantly share code, notes, and snippets.

@mahrous-amer
Created October 29, 2024 06:29
Show Gist options
  • Save mahrous-amer/b232720a40360bdfc20cadb9635151c0 to your computer and use it in GitHub Desktop.
Save mahrous-amer/b232720a40360bdfc20cadb9635151c0 to your computer and use it in GitHub Desktop.
A Bash utility script for managing a local PostgreSQL Docker container with ease.
#!/bin/bash
# Environment Variables
CONTAINER_NAME="dev-postgres"
POSTGRES_IMAGE="postgres"
POSTGRES_PASSWORD="dev_password"
DATA_DIR="${HOME}/dev_postgres/"
# Display Help
Help()
{
echo "Usage: dev-postgres [-r|l|c|s|e|k|p|h]"
echo
echo "Options:"
echo " -r Pull the latest PostgreSQL image from Dockerhub."
echo " -l List local Docker images."
echo " -c Create a new ${CONTAINER_NAME} container."
echo " -s Start the ${CONTAINER_NAME} container."
echo " -e Access the ${CONTAINER_NAME} container shell."
echo " -k Stop and remove the ${CONTAINER_NAME} container."
echo " -p Access PostgreSQL CLI inside ${CONTAINER_NAME}."
echo " -h Display this help message."
}
# Check if Docker is installed
if ! command -v docker &> /dev/null; then
echo "Docker is not installed. Please install Docker first."
exit 1
fi
# Handle options
while getopts ":hrlcsepk" option; do
case $option in
h) # Display Help
Help
exit;;
r) # Pull PostgreSQL image from Dockerhub
echo "Pulling latest PostgreSQL image..."
docker pull $POSTGRES_IMAGE
;;
l) # List local images
docker images
;;
c) # Create and run container with persistent storage
mkdir -p $DATA_DIR
docker run -d \
--name $CONTAINER_NAME \
-e POSTGRES_PASSWORD=$POSTGRES_PASSWORD \
-v ${DATA_DIR}:/var/lib/postgresql/data \
-p 5432:5432 \
$POSTGRES_IMAGE
echo "Container ${CONTAINER_NAME} created and running."
;;
s) # Start container
docker start $CONTAINER_NAME
;;
e) # Access container shell
docker exec -it $CONTAINER_NAME bash
;;
p) # Access PostgreSQL CLI inside container
docker exec -it $CONTAINER_NAME psql -U postgres
;;
k) # Stop and remove container safely
if docker ps -a --format '{{.Names}}' | grep -Eq "^${CONTAINER_NAME}$"; then
docker stop $CONTAINER_NAME
docker rm $CONTAINER_NAME
echo "Container ${CONTAINER_NAME} stopped and removed."
else
echo "Container ${CONTAINER_NAME} does not exist."
fi
;;
\?) # Invalid option
echo "Error: Invalid option"
Help
exit 1;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment