了解和使用MySQL服务启动脚本

14次阅读

共计 2034 个字符,预计需要花费 6 分钟才能阅读完成。

MySQL在类 Unix 系统上安装时包含一个 mysql.server 启动脚本,它通过 mysqld_safe 命令来启动 MySQL 服务,但我们通常把这个启动脚本重命名为 mysqld 或者mysql

这个启动脚本在有些系统上安装时被默认注册,很方便使用,但在其他系统上因为没有必要就不是默认注册, 需要我们手动注册服务。

mysql.server启动脚本

我们可以很方便的调用这个启动脚本:

shell> mysql.server start | stop

mysql.server启动脚本先进入 MySQL 的注册目录,然后调用 mysqld_safe 命令,调用时会默认使用 /etc/my.cnf;~/my.cnf 两个配置文件,所以如果你想要更精确的控制启动,可以修改相关的配置文件。

我们可以查看启动脚本的内容:

shell> vim /home/work/mysql/support-files/mysql.server
# If you install MySQL on some other places than /usr/local/mysql, then you
# have to do one of the following things for this script to work:
#
# - Run this script from within the MySQL installation directory
# - Create a /etc/my.cnf file with the following information:
#   [mysqld]
#   basedir=<path-to-mysql-installation-directory>
# - Add the above to any other configuration file (for example ~/.my.ini)
#   and copy my_print_defaults to /usr/bin
# - Add the path to the mysql-installation-directory to the basedir variable
#   below.
#
basedir=/home/work/mysql/
datadir=/home/work/mysql/data/

可以看到默认的安装位置是 /usr/local/mysql,而我们很多人的安装路径可能跟这个不一致,如果你需要通过该启动脚本启动,需要在这个启动文件中修改basedir/datadir 的位置,默认为空。

启动选项

在使用时,启动脚本会从配置文件中读取 [mysql.server][mysqld]两处配置块的启动选项,因此我们一般设置为:

[mysqld]
datadir=/home/work/mysql/data/
socket=/home/work/mysql/tmp/mysql.sock
port=3306
user=mysql
pid-file=/home/work/mysql/tmp/mysqld.pid

[mysql.server]
basedir=/home/work/mysql

mysql.server启动脚本在命令行只支持 start|stop 两个参数,更多的参数通过配置文件来指定:

# 只支持这 4 种参数
[mysql.server]
basedir=MySQL 安装目录
datadir=MySQL 数据目录
pid-file= 存储 MySQL 服务进程 ID 的文件
service-startup-timeout= 等待启动成功的超时时间,默认为 900s,缺省时无限等待,超时时报错退出

如果 pid-file 不指定,默认在 data 目录下创建 ${host_name}.pid 文件,在指定时 [mysqld_safe] 配置块中的优先级最高,但启动脚本读取的是 [mysqld] 配置块,因此如果你使用启动脚本,可以在两个配置块里配置相同的内容。

使用 mysqladmin 关闭服务

除了启动脚本进行启动和关闭之外,我们还可以这么关闭服务:

shell> ~/mysql/bin/mysqladmin shutdown -p
Enter password: (这里输入 root 密码)

注册服务

简单来说就是将启动脚本放在系统级 service 服务下,并重命名为mysqld

shell> ln -S ~/mysql/support-files/mysql.server /etc/init.d/mysqld
shell> service mysqld start|stop|status

具体注册详情参考我的另一篇文章:用 service 命令管理 mysql 启停。

开机自启动

我们也可以设置相关的开机自启动:

shell> chkconfig --add mysqld
shell> chkconfig --list

参考资料

  1. 4.3.3 mysql.server — MySQL Server Startup Script: https://dev.mysql.com/doc/ref…
  2. 用 service 命令管理 mysql 启停: https://segmentfault.com/a/11…
正文完
 0