0
点赞
收藏
分享

微信扫一扫

mysql怎么设置开机启动

MySQL是一个常用的关系型数据库管理系统,可以在服务器上存储和管理数据。在某些情况下,我们可能需要设置MySQL在服务器启动时自动运行,以便数据库服务在服务器启动后立即可用。

下面是在Linux系统上设置MySQL开机启动的步骤:

  1. 确保MySQL已经安装并且可以正常运行。

  2. 使用root权限登录服务器。

  3. 打开终端,执行以下命令,编辑MySQL的启动脚本文件:

sudo vi /etc/init.d/mysql
  1. 在编辑器中,输入以下脚本内容:
#!/bin/bash
### BEGIN INIT INFO
# Provides: mysql
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: $network $named
# Should-Stop: $network $named
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop the mysql database server daemon
### END INIT INFO

# Path to the database directory
datadir=/var/lib/mysql

# Path to the mysql installation
exec=/usr/sbin/mysqld

# Path to the mysql configuration file
conf=/etc/mysql/my.cnf

# The user that runs the mysql process
user=mysql

# The mysql process options
flags="--defaults-file=$conf --basedir=/usr"

# Check if the executable is present
test -x $exec || exit 0

set -e

case "$1" in
    start)
        echo -n "Starting MySQL: "
        mkdir -p $datadir
        /sbin/start-stop-daemon --start --quiet --user $user --exec $exec -- $flags --datadir=$datadir
        echo "done."
        ;;
    stop)
        echo -n "Stopping MySQL: "
        /sbin/start-stop-daemon --stop --quiet --user $user --exec $exec
        echo "done."
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit 0
  1. 保存并关闭文件。

  2. 授权启动脚本文件:

sudo chmod +x /etc/init.d/mysql
  1. 使用以下命令将MySQL添加到系统服务中:
sudo update-rc.d mysql defaults

执行该命令后,MySQL将被自动启动并在系统启动时运行。

现在,MySQL已经设置为开机启动。你可以重启服务器以验证MySQL是否会在服务器启动后自动运行。

除了上述步骤之外,还可以使用Systemd来设置MySQL的开机启动。

以下是在CentOS 7上使用Systemd设置MySQL开机启动的步骤:

  1. 确保MySQL已经安装并且可以正常运行。

  2. 使用root权限登录服务器。

  3. 打开终端,执行以下命令,创建一个MySQL服务文件:

sudo vi /etc/systemd/system/mysql.service
  1. 在编辑器中,输入以下内容:
[Unit]
Description=MySQL Server
After=network.target

[Service]
ExecStart=/usr/sbin/mysqld --defaults-file=/etc/mysql/my.cnf --basedir=/usr
User=mysql
Group=mysql
WorkingDirectory=/usr
Restart=always
RestartSec=3
LimitNOFILE=infinity

[Install]
WantedBy=multi-user.target
  1. 保存并关闭文件。

  2. 重新加载Systemd配置:

sudo systemctl daemon-reload
  1. 启用MySQL服务:
sudo systemctl enable mysql.service
  1. 使用以下命令启动MySQL服务:
sudo systemctl start mysql.service

现在,MySQL已经设置为开机启动。你可以重启服务器以验证MySQL是否会在服务器启动后自动运行。

以上是在Linux系统上设置MySQL开机启动的详细步骤。无论是通过编辑启动脚本文件还是使用Systemd,都可以确保MySQL在服务器启动时自动运行。

举报

相关推荐

0 条评论