Why I cannot create a db in my entrypoint script for mariadb?

31 Views Asked by At

I made the following script:

#!/bin/bash
set -e

# Define the name of the additional database
ADDITIONAL_DB_NAME="test_${MYSQL_DATABASE}"

# Perform the initialization of the additional database
echo "Creating additional database: $ADDITIONAL_DB_NAME"
mysql -uroot -p"$MYSQL_ROOT_PASSWORD" <<-EOSQL
    CREATE DATABASE IF NOT EXISTS \`$ADDITIONAL_DB_NAME\`;
    CREATE USER IF NOT EXISTS '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD';
    GRANT ALL PRIVILEGES ON \`$ADDITIONAL_DB_NAME\`.* TO '$MYSQL_USER'@'%';
    FLUSH PRIVILEGES;
EOSQL

I named it provision/mariadb/create-test-db.sh and in my docker-compose.yaml I mount it as a volume:

  mariadb:
    # Replace with your own
    image: mariadb
    command:
      --max_allowed_packet=64M
      --optimizer_use_condition_selectivity=1
      --optimizer_switch="rowid_filter=off"
    networks:
      private:
      public:
        ipv4_address: ${IP_BASE}.3
    env_file: env/db.env
    volumes:
      - ./volumes/db:/var/lib/mysql
      - ./provision/mariadb/create-test-db.sh:/docker-entrypoint-initdb.d/create-test-db.sh

That it tries to create an extra db prefixed with test_ but once I run it I get the error:

2024-02-12 14:01:56+00:00 [Note] [Entrypoint]: /usr/local/bin/docker-entrypoint.sh: sourcing /docker-entrypoint-initdb.d/create-test-db.sh
Creating additional database: test_php_app
ERROR 2002 (HY000): Can't connect to server on 'mariadb' (115)

How I can fix that?

1

There are 1 best solutions below

1
Dimitrios Desyllas On

Looking the original entrypoint I found this:

https://github.com/MariaDB/mariadb-docker/blob/b458c64747aa9e330c4e3443faf80964a63f2dd1/docker-entrypoint.sh#L296-L303

What it does the entrypoint it sources and shell files located at /docker-entrypoint-initdb.d. Meaning that this function can be accessible in your script as well:

#!/usr/bin/env bash

set -e

# Define the name of the additional database
ADDITIONAL_DB_NAME="test_${MYSQL_DATABASE}"


# Perform the initialization of the additional database
echo "Creating additional database: $ADDITIONAL_DB_NAME"
docker_process_sql -uroot -p"$MYSQL_ROOT_PASSWORD" <<-EOSQL
    CREATE DATABASE IF NOT EXISTS \`$ADDITIONAL_DB_NAME\`;
    CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\`;
    CREATE USER IF NOT EXISTS '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD';
    GRANT ALL PRIVILEGES ON \`$ADDITIONAL_DB_NAME\`.* TO '$MYSQL_USER'@'%';
    FLUSH PRIVILEGES;
EOSQL

Resulting a fix into your problem.