本文档风哥主要介绍systemd服务配置文件的使用,包括.service文件的概念、.service文件结构、.service文件存放位置、服务配置文件在生产环境的规划、服务配置文件最佳实践、服务配置文件安全配置建议、.service文件基础配置详解、.service文件高级配置详解、自定义服务配置实战、创建自定义服务实战案例、修改现有服务配置实战案例、服务配置故障排查与解决等内容,参考Red Hat Enterprise Linux 10官方文档,适合Linux运维人员在学习和测试中使用,如果要应用于生产环境则需要自行确认。
Part01-基础概念与理论知识
1.1 .service文件的概念
.service文件是systemd服务单元的配置文件,用于定义服务的启动、停止、重启等行为。.service文件使用INI格式,包含多个部分(section),每个部分包含多个键值对(key-value pairs)。.service文件是systemd服务管理的核心,正确配置.service文件对于服务的正常运行至关重要。更多视频教程www.fgedu.net.cn
- 使用INI格式
- 包含多个部分(section)
- 定义服务的启动、停止、重启行为
- 支持依赖关系配置
- 支持资源限制配置
1.2 .service文件结构
.service文件结构:
- [Unit]部分:定义服务的基本信息,如描述、依赖关系等
- [Service]部分:定义服务的启动、停止、重启行为
- [Install]部分:定义服务的安装信息,如启动目标等
1.3 .service文件存放位置
.service文件存放位置:
- /usr/lib/systemd/system/:系统默认服务配置文件
- /etc/systemd/system/:自定义服务配置文件(优先级更高)
- /run/systemd/system/:运行时服务配置文件
Part02-生产环境规划与建议
2.1 服务配置文件在生产环境的规划
服务配置文件在生产环境的规划要点:
– 使用/etc/systemd/system/存放自定义配置
– 使用/usr/lib/systemd/system/存放系统默认配置
– 使用systemctl edit创建覆盖配置
– 定期备份服务配置文件
– 记录配置变更历史
# 服务配置文件注意事项
– 了解服务依赖关系
– 配置正确的启动顺序
– 设置合理的超时时间
– 配置资源限制
– 配置安全选项
2.2 服务配置文件最佳实践
服务配置文件最佳实践:
- 自定义配置:使用/etc/systemd/system/存放自定义配置
- 覆盖配置:使用systemctl edit创建覆盖配置
- 依赖管理:合理配置服务依赖关系
- 资源限制:配置资源限制
- 安全加固:启用安全加固选项
2.3 服务配置文件安全配置建议
服务配置文件安全配置建议:
- 最小权限:使用最小权限运行服务
- 资源限制:配置资源限制
- 安全加固:启用安全加固选项
- 日志审计:启用日志审计
- 访问控制:配置访问控制
Part03-生产环境项目实施方案
3.1 .service文件基础配置详解
3.1.1 [Unit]部分配置
[Unit]
Description=nginx – high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
Wants=network.target
# 配置说明:
# Description:服务描述
# Documentation:服务文档链接
# After:定义服务启动顺序,在指定服务之后启动
# Wants:定义弱依赖关系
3.1.2 [Service]部分配置
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
# 配置说明:
# Type:服务类型(simple, forking, oneshot, dbus, notify, idle)
# PIDFile:PID文件路径
# ExecStartPre:启动前执行的命令
# ExecStart:启动命令
# ExecReload:重新加载命令
# ExecStop:停止命令
# PrivateTmp:使用私有临时目录
3.1.3 [Install]部分配置
[Install]
WantedBy=multi-user.target
# 配置说明:
# WantedBy:定义服务安装目标
# multi-user.target:多用户模式
# graphical.target:图形界面模式
3.2 .service文件高级配置详解
3.2.1 服务类型配置
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/app/server.py
# forking类型:派生服务,后台运行
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStart=/usr/sbin/nginx
# oneshot类型:一次性服务
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
RemainAfterExit=yes
# notify类型:通知服务
[Service]
Type=notify
ExecStart=/usr/sbin/myapp
# dbus类型:D-Bus服务
[Service]
Type=dbus
BusName=com.example.myapp
ExecStart=/usr/sbin/myapp
3.2.2 重启策略配置
[Service]
Restart=on-failure
RestartSec=5
StartLimitInterval=60
StartLimitBurst=3
# 配置说明:
# Restart:重启策略(no, on-success, on-failure, on-abnormal, on-watchdog, on-abort, always)
# RestartSec:重启间隔时间(秒)
# StartLimitInterval:启动限制时间间隔(秒)
# StartLimitBurst:启动限制次数
# 常用重启策略:
# no:不重启(默认)
# on-success:正常退出时重启
# on-failure:异常退出时重启
# on-abnormal:异常信号退出时重启
# on-watchdog:看门狗超时退出时重启
# on-abort:被信号中止时重启
# always:总是重启
3.2.3 资源限制配置
[Service]
CPUQuota=50%
MemoryLimit=512M
TasksMax=100
# 配置说明:
# CPUQuota:CPU使用配额(百分比)
# MemoryLimit:内存限制
# TasksMax:最大任务数
# 其他资源限制选项:
# CPUShares:CPU份额
# MemoryAccounting:启用内存统计
# CPUAccounting:启用CPU统计
# BlockIOAccounting:启用块IO统计
3.3 自定义服务配置实战
3.3.1 创建自定义服务
# cat > /usr/local/bin/myapp.sh << 'EOF' #!/bin/bash # 自定义服务脚本 echo "Starting myapp..." while true; do echo "myapp is running at $(date)" sleep 10 done EOF # 2. 设置脚本执行权限 # chmod +x /usr/local/bin/myapp.sh # 3. 创建服务配置文件 # cat > /etc/systemd/system/myapp.service << 'EOF' [Unit] Description=My Application Service After=network.target [Service] Type=simple ExecStart=/usr/local/bin/myapp.sh Restart=always RestartSec=5 User=nobody Group=nobody [Install] WantedBy=multi-user.target EOF # 4. 重新加载systemd配置 # systemctl daemon-reload # 5. 启动服务 # systemctl start myapp # 6. 查看服务状态 # systemctl status myapp ● myapp.service - My Application Service Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: disabled) Active: active (running) since Thu 2026-03-31 10:00:00 CST; 5s ago Main PID: 1234 (myapp.sh) Tasks: 2 (limit: 4915) Memory: 1.2M CGroup: /system.slice/myapp.service ├─1234 /bin/bash /usr/local/bin/myapp.sh └─1235 sleep 10 Mar 31 10:00:00 localhost systemd[1]: Started My Application Service. Mar 31 10:00:00 localhost myapp.sh[1234]: Starting myapp... Mar 31 10:00:00 localhost myapp.sh[1234]: myapp is running at Thu Mar 31 10:00:00 CST 2026 # 7. 启用服务 # systemctl enable myapp Created symlink /etc/systemd/system/multi-user.target.wants/myapp.service → /etc/systemd/system/myapp.service. # 8. 查看服务日志 # journalctl -u myapp -f -- Logs begin at Thu 2026-03-31 10:00:00 CST. -- Mar 31 10:00:00 localhost systemd[1]: Started My Application Service. Mar 31 10:00:00 localhost myapp.sh[1234]: Starting myapp... Mar 31 10:00:00 localhost myapp.sh[1234]: myapp is running at Thu Mar 31 10:00:00 CST 2026 Mar 31 10:00:10 localhost myapp.sh[1234]: myapp is running at Thu Mar 31 10:00:10 CST 2026 Mar 31 10:00:20 localhost myapp.sh[1234]: myapp is running at Thu Mar 31 10:00:20 CST 2026
Part04-生产案例与实战讲解
4.1 创建自定义服务实战案例
4.1.1 完整创建流程
# mkdir -p /opt/mywebapp
# 2. 创建应用脚本
# cat > /opt/mywebapp/app.py << 'EOF'
#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'
Hello from MyWebApp!
‘)
if __name__ == ‘__main__’:
server = HTTPServer((‘0.0.0.0’, 8080), MyHandler)
print(‘Starting server on port 8080…’)
server.serve_forever()
EOF
# 3. 设置脚本执行权限
# chmod +x /opt/mywebapp/app.py
# 4. 创建服务配置文件
# cat > /etc/systemd/system/mywebapp.service << 'EOF'
[Unit]
Description=My Web Application
After=network.target
[Service]
Type=simple
User=nobody
Group=nobody
WorkingDirectory=/opt/mywebapp
ExecStart=/usr/bin/python3 /opt/mywebapp/app.py
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=mywebapp
[Install]
WantedBy=multi-user.target
EOF
# 5. 重新加载systemd配置
# systemctl daemon-reload
# 6. 启动服务
# systemctl start mywebapp
# 7. 查看服务状态
# systemctl status mywebapp
● mywebapp.service - My Web Application
Loaded: loaded (/etc/systemd/system/mywebapp.service; disabled; vendor preset: disabled)
Active: active (running) since Thu 2026-03-31 10:00:00 CST; 5s ago
Main PID: 1234 (python3)
Tasks: 2 (limit: 4915)
Memory: 8.5M
CGroup: /system.slice/mywebapp.service
└─1234 /usr/bin/python3 /opt/mywebapp/app.py
Mar 31 10:00:00 localhost systemd[1]: Started My Web Application.
Mar 31 10:00:00 localhost mywebapp[1234]: Starting server on port 8080...
# 8. 测试服务
# curl http://localhost:8080
Hello from MyWebApp!
# 9. 启用服务
# systemctl enable mywebapp
Created symlink /etc/systemd/system/multi-user.target.wants/mywebapp.service → /etc/systemd/system/mywebapp.service.
# 10. 查看服务日志
# journalctl -u mywebapp
— Logs begin at Thu 2026-03-31 09:00:00 CST. —
Mar 31 10:00:00 localhost systemd[1]: Started My Web Application.
Mar 31 10:00:00 localhost mywebapp[1234]: Starting server on port 8080…
Mar 31 10:00:05 localhost mywebapp[1234]: 127.0.0.1 – – [31/Mar/2026 10:00:05] “GET / HTTP/1.1” 200 –
4.2 修改现有服务配置实战案例
4.2.1 使用systemctl edit修改配置
# systemctl cat nginx
# /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx – high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
Wants=network.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
# 2. 使用systemctl edit创建覆盖配置
# systemctl edit nginx
# 3. 添加自定义配置
# cat > /etc/systemd/system/nginx.service.d/override.conf << 'EOF'
[Service]
Restart=on-failure
RestartSec=5
CPUQuota=50%
MemoryLimit=512M
EOF
# 4. 重新加载systemd配置
# systemctl daemon-reload
# 5. 查看合并后的配置
# systemctl cat nginx
# /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
Wants=network.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/nginx.service.d/override.conf
[Service]
Restart=on-failure
RestartSec=5
CPUQuota=50%
MemoryLimit=512M
# 6. 重启服务
# systemctl restart nginx
# 7. 查看服务状态
# systemctl status nginx
● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Drop-In: /etc/systemd/system/nginx.service.d
└─override.conf
Active: active (running) since Thu 2026-03-31 10:00:00 CST; 5s ago
# 8. 删除覆盖配置
# rm -rf /etc/systemd/system/nginx.service.d/
# systemctl daemon-reload
# systemctl restart nginx
4.3 服务配置故障排查与解决
4.3.1 服务配置语法错误
# 分析步骤:
# 1. 查看错误信息
# systemctl start myapp
Job for myapp.service failed because the control process exited with error code.
See “systemctl status myapp.service” and “journalctl -xe” for details.
# 2. 查看服务状态
# systemctl status myapp
● myapp.service – My Application Service
Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Thu 2026-03-31 10:00:00 CST; 5s ago
Mar 31 10:00:00 localhost systemd[1]: Starting My Application Service…
Mar 31 10:00:00 localhost systemd[1234]: myapp.service: Failed to parse service type, ignoring: simplee
Mar 31 10:00:00 localhost systemd[1234]: myapp.service: Service has no ExecStart= setting, which is required for simple services. Refusing.
Mar 31 10:00:00 localhost systemd[1]: myapp.service: Control process exited, code=exited status=1
Mar 31 10:00:00 localhost systemd[1]: myapp.service: Failed with result ‘exit-code’.
Mar 31 10:00:00 localhost systemd[1]: Failed to start My Application Service.
# 3. 检查配置文件语法
# cat /etc/systemd/system/myapp.service
[Unit]
Description=My Application Service
After=network.target
[Service]
Type=simplee
ExecStart=/usr/local/bin/myapp.sh
[Install]
WantedBy=multi-user.target
# 4. 修复配置文件
# cat > /etc/systemd/system/myapp.service << 'EOF'
[Unit]
Description=My Application Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/myapp.sh
[Install]
WantedBy=multi-user.target
EOF
# 5. 重新加载systemd配置
# systemctl daemon-reload
# 6. 启动服务
# systemctl start myapp
# 7. 验证服务已启动
# systemctl status myapp
● myapp.service - My Application Service
Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: disabled)
Active: active (running) since Thu 2026-03-31 10:00:00 CST; 5s ago
# 8. 预防措施
# - 检查配置文件语法
# - 使用systemd-analyze verify验证配置
# - 备份配置文件
Part05-风哥经验总结与分享
5.1 服务配置文件经验总结
服务配置文件经验总结:
- 自定义配置:使用/etc/systemd/system/存放自定义配置
- 覆盖配置:使用systemctl edit创建覆盖配置
- 依赖管理:合理配置服务依赖关系
- 资源限制:配置资源限制
- 安全加固:启用安全加固选项
5.2 服务配置文件检查清单
服务配置文件检查清单:
- 配置前:了解服务需求、规划配置
- 配置时:检查配置文件语法
- 配置后:验证服务状态
- 使用时:定期检查服务状态
- 维护时:定期更新服务配置
- 故障排查:查看详细日志、检查配置文件
5.3 服务配置文件相关工具推荐
服务配置文件相关工具推荐:
- systemctl:systemd控制命令
- systemd-analyze:systemd分析工具
- journalctl:systemd日志查看命令
- systemd-delta:配置差异比较工具
- systemd-cgls:控制组列表工具
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
