#!/usr/bin/env bash # User-configurable variables containerName="postgres-db-name" postgresUser="postgres-user" postgresPassword="postgres-password" postgresDB="postgres-db" hostPort=5432 containerPort=5432 # Function to create a new container create_container() { echo "Creating container '$containerName'..." docker run \ --name "$containerName" \ -e POSTGRES_USER="$postgresUser" \ -e POSTGRES_PASSWORD="$postgresPassword" \ -e POSTGRES_DB="$postgresDB" \ -p "$hostPort:$containerPort" \ -d postgres } # Function to start an existing container start_container() { echo "Starting container '$containerName'..." docker start "$containerName" } # Main script logic # Check whether the container exists (in any state) containerExists=$(docker ps -a --filter "name=$containerName" --format "{{.Names}}") if [ -n "$containerExists" ]; then # Container exists, check if it's running containerRunning=$(docker ps --filter "name=$containerName" --filter "status=running" --format "{{.Names}}") if [ -n "$containerRunning" ]; then echo "Container '$containerName' is already running." else echo "Container '$containerName' exists but is not running." if ! start_container; then echo "Failed to start container '$containerName'. Removing and recreating it..." docker rm "$containerName" create_container fi fi else # Container does not exist, create it create_container fi