biscuide revised this gist . Go to revision
No changes
biscuide revised this gist . Go to revision
1 file changed, 54 insertions
startDockerPostgreSQL.bash(file created)
| @@ -0,0 +1,54 @@ | |||
| 1 | + | #!/usr/bin/env bash | |
| 2 | + | ||
| 3 | + | # User-configurable variables | |
| 4 | + | containerName="postgres-db-name" | |
| 5 | + | postgresUser="postgres-user" | |
| 6 | + | postgresPassword="postgres-password" | |
| 7 | + | postgresDB="postgres-db" | |
| 8 | + | ||
| 9 | + | hostPort=5432 | |
| 10 | + | containerPort=5432 | |
| 11 | + | ||
| 12 | + | ||
| 13 | + | # Function to create a new container | |
| 14 | + | create_container() { | |
| 15 | + | echo "Creating container '$containerName'..." | |
| 16 | + | docker run \ | |
| 17 | + | --name "$containerName" \ | |
| 18 | + | -e POSTGRES_USER="$postgresUser" \ | |
| 19 | + | -e POSTGRES_PASSWORD="$postgresPassword" \ | |
| 20 | + | -e POSTGRES_DB="$postgresDB" \ | |
| 21 | + | -p "$hostPort:$containerPort" \ | |
| 22 | + | -d postgres | |
| 23 | + | } | |
| 24 | + | ||
| 25 | + | ||
| 26 | + | # Function to start an existing container | |
| 27 | + | start_container() { | |
| 28 | + | echo "Starting container '$containerName'..." | |
| 29 | + | docker start "$containerName" | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | ||
| 33 | + | # Main script logic | |
| 34 | + | ||
| 35 | + | # Check whether the container exists (in any state) | |
| 36 | + | containerExists=$(docker ps -a --filter "name=$containerName" --format "{{.Names}}") | |
| 37 | + | ||
| 38 | + | if [ -n "$containerExists" ]; then | |
| 39 | + | # Container exists, check if it's running | |
| 40 | + | containerRunning=$(docker ps --filter "name=$containerName" --filter "status=running" --format "{{.Names}}") | |
| 41 | + | if [ -n "$containerRunning" ]; then | |
| 42 | + | echo "Container '$containerName' is already running." | |
| 43 | + | else | |
| 44 | + | echo "Container '$containerName' exists but is not running." | |
| 45 | + | if ! start_container; then | |
| 46 | + | echo "Failed to start container '$containerName'. Removing and recreating it..." | |
| 47 | + | docker rm "$containerName" | |
| 48 | + | create_container | |
| 49 | + | fi | |
| 50 | + | fi | |
| 51 | + | else | |
| 52 | + | # Container does not exist, create it | |
| 53 | + | create_container | |
| 54 | + | fi | |
Newer
Older