1#!/usr/bin/env bash
2# Use this script to start a docker container for a local development database
3
4# TO RUN ON WINDOWS:
5# 1. Install WSL (Windows Subsystem for Linux) - https://learn.microsoft.com/en-us/windows/wsl/install
6# 2. Install Docker Desktop or Podman Deskop
7# - Docker Desktop for Windows - https://docs.docker.com/docker-for-windows/install/
8# - Podman Desktop - https://podman.io/getting-started/installation
9# 3. Open WSL - `wsl`
10# 4. Run this script - `./start-database.sh`
11
12# On Linux and macOS you can run this script directly - `./start-database.sh`
13
14set -a
15source .env
16
17DB_PASSWORD=$(echo "$DATABASE_URL" | awk -F':' '{print $3}' | awk -F'@' '{print $1}')
18DB_PORT=$(echo "$DATABASE_URL" | awk -F':' '{print $4}' | awk -F'\/' '{print $1}')
19DB_NAME=$(echo "$DATABASE_URL" | awk -F'/' '{print $4}')
20DB_CONTAINER_NAME="$DB_NAME-postgres"
21
22if ! [ -x "$(command -v docker)" ] && ! [ -x "$(command -v podman)" ]; then
23 echo -e "Docker or Podman is not installed. Please install docker or podman and try again.\nDocker install guide: https://docs.docker.com/engine/install/\nPodman install guide: https://podman.io/getting-started/installation"
24 exit 1
25fi
26
27# determine which docker command to use
28if [ -x "$(command -v docker)" ]; then
29 DOCKER_CMD="docker"
30elif [ -x "$(command -v podman)" ]; then
31 DOCKER_CMD="podman"
32fi
33
34if ! $DOCKER_CMD info > /dev/null 2>&1; then
35 echo "$DOCKER_CMD daemon is not running. Please start $DOCKER_CMD and try again."
36 exit 1
37fi
38
39if command -v nc >/dev/null 2>&1; then
40 if nc -z localhost "$DB_PORT" 2>/dev/null; then
41 echo "Port $DB_PORT is already in use."
42 exit 1
43 fi
44else
45 echo "Warning: Unable to check if port $DB_PORT is already in use (netcat not installed)"
46 read -p "Do you want to continue anyway? [y/N]: " -r REPLY
47 if ! [[ $REPLY =~ ^[Yy]$ ]]; then
48 echo "Aborting."
49 exit 1
50 fi
51fi
52
53if [ "$($DOCKER_CMD ps -q -f name=$DB_CONTAINER_NAME)" ]; then
54 echo "Database container '$DB_CONTAINER_NAME' already running"
55 exit 0
56fi
57
58if [ "$($DOCKER_CMD ps -q -a -f name=$DB_CONTAINER_NAME)" ]; then
59 $DOCKER_CMD start "$DB_CONTAINER_NAME"
60 echo "Existing database container '$DB_CONTAINER_NAME' started"
61 exit 0
62fi
63
64if [ "$DB_PASSWORD" == "password" ]; then
65 echo "You are using the default database password"
66 read -p "Should we generate a random password for you? [y/N]: " -r REPLY
67 if ! [[ $REPLY =~ ^[Yy]$ ]]; then
68 echo "Please change the default password in the .env file and try again"
69 exit 1
70 fi
71 # Generate a random URL-safe password
72 DB_PASSWORD=$(openssl rand -base64 12 | tr '+/' '-_')
73 sed -i '' "s#:password@#:$DB_PASSWORD@#" .env
74fi
75
76$DOCKER_CMD run -d \
77 --name $DB_CONTAINER_NAME \
78 -e MYSQL_ROOT_PASSWORD="$DB_PASSWORD" \
79 -e MYSQL_DATABASE="$DB_NAME" \
80 -p "$DB_PORT":3306 \
81 docker.io/mysql && echo "Database container '$DB_CONTAINER_NAME' was successfully created"