Last active 1742658636

Helper script to start/create a docker PostgreSQL DB

startDockerPostgreSQL.bash Raw
1#!/usr/bin/env bash
2
3# User-configurable variables
4containerName="postgres-db-name"
5postgresUser="postgres-user"
6postgresPassword="postgres-password"
7postgresDB="postgres-db"
8
9hostPort=5432
10containerPort=5432
11
12
13# Function to create a new container
14create_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
27start_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)
36containerExists=$(docker ps -a --filter "name=$containerName" --format "{{.Names}}")
37
38if [ -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
51else
52 # Container does not exist, create it
53 create_container
54fi
55