Tag Archives: Docker

MySQL Docker helper script

Here is a little script I made to help me start/stop and remove a MySQL docker instance. The script also points to an init file (docker-entrypoint-initdb.d) for the database where you can put all the creations of init objects needed, eg. CREATE TABLE…, INSERT INTO…, and so on

Usage:

>my-docker-db-script start # Starts MySQL docker instance. Creates it if it does not exist
>my-docker-db-script stop # Stops the MySQL docker instance
>my-docker-db-script remove # Removes the MySQL instance

Bash script:

#!/bin/bash

name="my-mysql-db"
command="$1"

function start() {
 state=$(2>/dev/null docker inspect $name --format '{{ .State.Status }}' || echo "")

 if [[ "$state" == "running" ]]; then
  echo "Databse already running!"
  exit 1
 fi
 
 if [[ "$state" == "exited" ]]; then
  echo "Database already exists. Starting..."
  docker start $name && echo "  ... database started"
 else
  echo "No database exists. Creating..."
  docker run -d -p 3306:3306 --name $name \
   -e MYSQL_ROOT_PASSWORD=root \
   -e MYSQL_DATABASE=my_db \
   -e MYSQL_USERNAME=myusername \
   -e MYSQL_PASSWORD=myuserpassword \
   -v $(pwd)/my-mysql-db/mysql-docker-init:/docker-entrypoint-initdb.d \
   -d mysql:5.6.51 && echo "  ... database created"
 fi

}

function stop() {
 state=$(2>/dev/null docker inspect $name --format '{{ .State.Status }}' || echo "")

 if [[ "$state" == "" ]]; then
  echo "Database does not exist!"
  exit 1
 fi

 echo "Stopping database ..."
 docker stop $name && echo "  ... database stopped"
}

function remove() {
 state=$(2>/dev/null docker inspect $name --format '{{ .State.Status }}' || echo "")

 if [[ "$state" == "" ]]; then
  echo "Database does not exist!"
  exit 1
 fi

 echo "Removing database"
 if [[ "$state" == "running" ]]; then
  docker stop $name && echo "  ...database stopped"
 fi

 docker rm $name && echo "   ...database removed"
}

case "$command" in
 start)
  start
  ;;
 stop)
  stop
  ;;
 remove)
  remove
  ;;
 *)
  echo "Invalid command: ${command}. Usage $0 (start|stop|remove)"
  exit 1
esac 

Tested on MySQL v5.6.51, OSX 10.15.7 and Docker Desktop 4.3.2