Linux平台如何配置systemd授权mysql用户管理MySQL服务

在Linux系统中,默认情况下,mysql用户是没有权限启动MySQL服务的,需要root配置/etc/sudoers文件,才能给mysql用户授权。

配置MySQL服务

1
2
3
cd /usr/lib/systemd/system
touch mysqld.service
chmod 644 mysqld.service

编辑mysqld.service

在其中输入如下信息,修改其中一些配置(有些内容,请根据实际情况设置/调整)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html
After=network.target
After=syslog.target
 
[Install]
WantedBy=multi-user.target
 
[Service]
User=mysql
Group=mysql
 
# Have mysqld write its state to the systemd notify socket
Type=notify
 
# Disable service start and stop timeout logic of systemd for mysqld service.
TimeoutSec=0
 
# Start main service
ExecStart=/opt/mysql/mysql8/bin/mysqld --defaults-file=/data/mysql/conf/my.cnf $MYSQLD_OPTS
 
# Use this to switch malloc implementation
EnvironmentFile=-/etc/sysconfig/mysql
 
# Sets open_files_limit
LimitNOFILE = 10000
 
Restart=on-failure
 
RestartPreventExitStatus=1
 
# Set environment variable MYSQLD_PARENT_PID. This is required for restart.
Environment=MYSQLD_PARENT_PID=1
 
PrivateTmp=false

配置systemd服务

1
2
3
4
systemctl daemon-reload
systemctl enable mysqld.service
systemctl is-enabled mysqld
systemctl start mysqld.service 

给mysql用户授权

在/etc/sudoers中添加下面配置

1
mysql   ALL=(ALL)       NOPASSWD: /usr/bin/systemctl start mysqld.service, /usr/bin/systemctl stop mysqld.service, /usr/bin/systemctl status mysqld.service

配置后mysql用户就能启动mysqld服务

1
systemctl start mysqld.service