使用systemd的服务配置浅析

使用systemd建立本身的服务

    CentOS 7的服务systemctl脚本存放在:/usr/lib/systemd/,有系统(system)和用户(user)之分,即:/usr/lib/systemd/system ,/usr/lib/systemd/user。
    每个服务以.service结尾,通常会分为3部分:[Unit]、[Service]和[Install],就以nginx为例分析。
nginx

建立service

在/usr/lib/systemd/system下建立nginx.service文件内容以下(也能够在/usr/lib/systemd/usr下建立):web

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
  
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
  
[Install]
WantedBy=multi-user.target

[Unit]

    Description : 服务的简单描述。shell

    Documentation : 服务文档。
socket

    After= : 依赖,仅当依赖的服务启动以后再启动自定义的服务单元。 测试

[Service]

  • Type : 启动类型simple、forking、oneshot、notify、dbus。spa

Type=simple(默认值):systemd认为该服务将当即启动。服务进程不会fork。若是该服务要启动其余服务,不要使用此类型启动,除非该 服务是socket激活型。 Type=forking:systemd认为当该服务进程fork,且父进程退出后服务启动成功。对于常规的守护进程(daemon),除非你肯定此启 动方式没法知足需求,使用此类型启动便可。使用此启动类型应同时指定 PIDFile=,以便systemd可以跟踪服务的主进程。 Type=oneshot:这一选项适用于只执行一项任务、随后当即退出的服务。可能须要同时设置 RemainAfterExit=yes 使得 systemd 在服务进程退出以后仍然认为服务处于激活状态。 Type=notify:与 Type=simple 相同,但约定服务会在就绪后向 systemd 发送一个信号。这一通知的实现由 libsystemd-daemon.so 提供。 Type=dbus:若以此方式启动,当指定的 BusName 出如今DBus系统总线上时,systemd认为服务就绪。
  1. PIDFile : pid文件路径 。.net

  2. ExecStartPre :启动前要作什么,上文中是测试配置文件 -t rest

  3. ExecStart:启动日志

  4. ExecReload:重载code

  5. ExecStop:中止

  6. PrivateTmp:True表示给服务分配独立的临时空间

[Install]

WantedBy:服务安装的用户模式,从字面上看,就是想要使用这个服务的有是谁?上文中使用的是:multi-user.target ,就是指想要使用这个服务的目录是多用户。「以上全是我的理解,瞎猜的,若有不当,请你们多多指教每个.target其实是连接到咱们单位文件的集合,当咱们执行:

$ sudo systemctl enable nginx.service
 

就会在/etc/systemd/system/multi-user.target.wants/目录下新建一个/usr/lib/systemd/system/nginx.service 文件的连接。

操做Service:

#启动服务
$ sudo systemctl start nginx.service
 
#查看日志
$ sudo journalctl -f -u nginx.service
-- Logs begin at 四 2015-06-25 17:32:20 CST. --
6月 25 10:28:24 Leco.lan systemd[1]: Starting nginx - high performance web server...
6月 25 10:28:24 Leco.lan nginx[7976]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
6月 25 10:28:24 Leco.lan nginx[7976]: nginx: configuration file /etc/nginx/nginx.conf test is successful
6月 25 10:28:24 Leco.lan systemd[1]: Started nginx - high performance web server.
 
#重启
$ sudo systemctl restart nginx.service
 
#重载
$ sudo systemctl reload nginx.service
 
#中止
$ sudo systemctl stop nginx.service
 

systemd科普

科普1:浅析 Linux 初始化 init 系统,Systemd

科普2:Getting Started with systemd

相关文章
相关标签/搜索