systemctl服务管理

systemd的相关命令

systemctl list-unit-files   #查看linux的开机自动开启的所有服务
systemd-analyze      # 查看启动耗时                                                                                  
systemd-analyze blame    # 查看每个服务的启动耗时
systemd-analyze critical-chain   # 显示瀑布状的启动过程流
systemd-analyze critical-chain atd.service    # 显示指定服务的启动流

systemd文件格式说明

systemd unit 文件通常是由三部分组成的

  1. [Unit] 定义的通用选项,比如描述信息,依赖关系等
  2. [Service] 定义服务的类型,具体的启动关闭重启选项都在此部分配置
  3. [Install] 定义由开机自启和不开机自启命令时实现的选项

type=simple和type=forking的区别

使用Type=forking时,要求ExecStart启动的命令自身就是以daemon模式运行的。

Type=simple是一种最常见的通过systemd服务系统运行用户自定义命令的类型,也是省略Type指令时的默认类型。只适合那些在shell下运行在前台的命令。也就是说,当一个命令本身会以daemon模式运行时,将不能使用simple,而应该使用Type=forking。比如ls命令、sleep命令、非daemon模式运行的nginx进程以及那些以前台调试模式运行的进程,在理论上都可以定义为simple类型的服务。

案例

定义一个nginx启动文件

cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target

systemctl daemon-reload
systemctl start  nginx
systemctl enable  nginx
systemctl status  nginx

定义一个java程序启动文件

cat /usr/lib/systemd/system/eladmin.service
[Unit]
Description=eladmin
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=simple
Environment=JAVA_HOME=/usr/local/jdk
ExecStart=/usr/local/jdk/bin/java -jar  /app/eladmin/eladmin-system-2.7.jar
Restart=on-failure

[Install]
WantedBy=multi-user.target
posted @ 2025-08-12 15:24  阿峰博客站  阅读(16)  评论(0)    收藏  举报