概述
systemd是目前Linux系统上主要的系统守护进程管理工具,由于init一方面对于进程的管理是串行化的,容易出现阻塞情况,另一方面init也仅仅是执行启动脚本,并不能对服务本身进行更多的管理。所以从CentOS 7 开始也由systemd取代了init作为默认的系统进程管理工具。
systemd所管理的所有系统资源都称作Unit,通过systemd命令集可以方便的对这些Unit进行管理。比如systemctl
、hostnamectl
、timedatectl
、localctl
等命令,这些命令虽然改写了init时代用户的命令使用习惯(不再使用chkconfig、service等命令),但确实也提供了很大的便捷性。
特点
语法
systemctl [OPTIONS...] {COMMAND} ...
command:
- start:启动指定的unit,例如
systemctl start Nginx
- stop:关闭指定的unit,例如
systemctl stop Nginx
- restart:重启指定unit,例如
systemctl restart Nginx
- reload:重载指定unit,例如
systemctl reload Nginx
- enable:系统开机时自动启动指定unit,前提是配置文件中有相关配置,例如
systemctl enable Nginx
- disable:开机时不自动运行指定unit,例如
systemctl disable Nginx
- status:查看指定unit当前运行状态,例如
systemctl status Nginx
配置说明
- 每一个Unit都需要有一个配置文件用于告知systemd对于服务的管理方式
- 配置文件存放于/usr/lib/systemd/system/,设置开机启动后会在/etc/systemd/system目录建立软链接文件
- 每个Unit的配置文件配置默认后缀名为
.service
- 在/usr/lib/systemd/system/目录中分为system和user两个目录,一般将开机不登陆就能运行的程序存在系统服务里,也就是/usr/lib/systemd/system
- 配置文件使用方括号分成了多个部分,并且区分大小写
相关文件说明:
相关文件 | CentOS6 | CentOS7 |
---|---|---|
服务启动的脚本启动路径 | /etc/init.d | /usr/lib/systemd/system |
开机自启服务存放路径 | /etc/rcN.d | /etc/systemd/system/multi-user.target.wants/ |
默认运行级别配置文件 | /etc/inittab | /etc/systemd/system/default.target |
常见中间件配置
Nginx
[Unit]
Description=Nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/Nginx/sbin/Nginx
ExecReload=/usr/local/Nginx/sbin/Nginx -s reload
ExecStop=/usr/local/Nginx/sbin/Nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
MysqL
[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
Type=forking
PIDFile=/var/run/MysqLd/MysqLd.pid
# Disable service start and stop timeout logic of systemd for MysqLd service.
TimeoutSec=0
# Execute pre and post scripts as root
PermissionsStartOnly=true
# Needed to create system tables
ExecStartPre=/usr/bin/MysqLd_pre_systemd
# Start main service
ExecStart=/usr/sbin/MysqLd --daemonize --pid-file=/var/run/MysqLd/MysqLd.pid $MysqLD_OPTS
# Use this to switch malloc implementation
EnvironmentFile=-/etc/sysconfig/MysqL
# Sets open_files_limit
LimitNOFILE = 5000
Restart=on-failure
RestartPreventExitStatus=1
PrivateTmp=false