MySQL-Docker/entrypoint.sh
2025-03-23 14:44:38 -05:00

74 lines
2.2 KiB
Bash

#!/bin/bash
set -e
# Create required MySQL directories
echo "Creating required MySQL directories..."
mkdir -p /var/lib/mysql /var/lib/mysql-files /var/run/mysqld
chown -R mysql:mysql /var/lib/mysql /var/lib/mysql-files /var/run/mysqld
chmod 750 /var/lib/mysql /var/lib/mysql-files
chmod 755 /var/run/mysqld
# Check if MySQL has been initialized
if [ ! "$(ls -A /var/lib/mysql/mysql)" ]; then
echo "Initializing MySQL data directory..."
# Initialize without root password
mysqld --initialize-insecure --user=mysql
# Start MySQL temporarily with --skip-networking to set root password
echo "Starting MySQL temporarily to set root password..."
mysqld --user=mysql --skip-networking &
pid="$!"
# Wait for MySQL to start up
echo "Waiting for temporary MySQL instance to start..."
for i in {30..0}; do
if mysqladmin ping --socket=/var/run/mysqld/mysqld.sock &> /dev/null; then
break
fi
echo "MySQL not ready yet... waiting"
sleep 1
done
if [ "$i" = 0 ]; then
echo >&2 "MySQL initialization process failed."
exit 1
fi
# Set root password
echo "Setting root password..."
mysql --socket=/var/run/mysqld/mysqld.sock -u root <<-EOSQL
ALTER USER 'root'@'localhost' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}';
FLUSH PRIVILEGES;
EOSQL
# Stop temporary MySQL server
echo "Stopping temporary MySQL instance..."
if ! mysqladmin shutdown --socket=/var/run/mysqld/mysqld.sock; then
kill "$pid"
wait "$pid"
fi
fi
# Start MySQL in the background
echo "Starting MySQL server..."
mysqld --user=mysql &
# Wait for MySQL to be ready
echo "Waiting for MySQL to be ready..."
until mysqladmin ping -h"localhost" -u"root" -p"${MYSQL_ROOT_PASSWORD}" --silent; do
echo "MySQL not ready yet... waiting"
sleep 2
done
echo "MySQL is ready!"
# Run the admin user creation script
echo "Creating admin user..."
/usr/local/bin/create_admin.sh
# Start cron service
echo "Starting cron service..."
service cron start
# Keep the container running by waiting on the MySQL process
echo "MySQL server is running. Container will stay alive until MySQL exits."
wait %1