bash 等待服务启动

bash 等待服务启动

我在使用 bash 脚本的第一部分时遇到了问题,我需要等待服务器 mysql 启动后才能执行 mysqadmin 命令...我无法可靠地让它工作!

#!/bin/bash

if [[ ! -f /var/lib/mysql/status.secured ]]; then
  echo "MariaDB -> secure"
  #
  /usr/sbin/service mysql start
  while "$(mysql -u root -e "select 1")" -ne 1; do
    sleep 1
  done
  #
  mysqladmin -u root password "$MARIA_ROOT_PASSWORD"
  mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "UPDATE mysql.user SET Password=PASSWORD('$MARIA_ROOT_PASSWORD') WHERE User='root'"
  mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')"
  mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "DELETE FROM mysql.user WHERE User=''"
  mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%'"
  mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "FLUSH PRIVILEGES"
  touch /var/lib/mysql/status.secured
  #
  /usr/sbin/service mysql stop
  while [[ "$(/usr/sbin/service mysql status)" != " * MariaDB is stopped." ]]; do
    sleep 1
  done
  echo "MariaDB -> secured"
fi

它是基于 ubuntu 的 docker 容器,phusion/baseimage

答案1

我认为这会起作用:

#!/bin/bash

if [[ ! -f /var/lib/mysql/status.secured ]]; then
  echo "MariaDB -> secure"
  #
  /usr/sbin/service mysql start
  #give up if not started in 2min
  if mysqladmin --wait=120 -u root password "$MARIA_ROOT_PASSWORD"; then
    mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "UPDATE mysql.user SET Password=PASSWORD('$MARIA_ROOT_PASSWORD') WHERE User='root'"
    mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')"
    mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "DELETE FROM mysql.user WHERE User=''"
    mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%'"
    mysql -u root -p"$MARIA_ROOT_PASSWORD" -e "FLUSH PRIVILEGES"
    touch /var/lib/mysql/status.secured
    /usr/sbin/service mysql stop
    while [[ "$(/usr/sbin/service mysql status)" != " * MariaDB is stopped." ]]; do
      sleep 1
    done
    echo "MariaDB -> secured"
  else
    echo Gave up waiting for mysqld to respond
    /usr/sbin/service mysql stop
  fi

fi

答案2

您还可以使用 docker-compose 并使用命令启动容器并依赖于服务健康

相关内容