// PC530 技术论坛 v1.0
● online 登录 / 注册
返回列表
运维与云原生 #运维

【运维】Linux 服务器实战(4):systemd 服务与 journal 日志


Linux 服务器实战 · 第 4 篇
服务起不来、要看日志——Ubuntu 22.04/24.04 默认 systemd + journald


1. systemctl 必备

sudo systemctl status nginx --no-pager
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx      # 重载配置,适合 nginx
sudo systemctl enable nginx      # 开机自启
sudo systemctl disable nginx
sudo systemctl is-enabled nginx
查看 unit 文件:

```bash
systemctl cat nginx  
systemctl list-units --type=service --state=running
---

## 2. journalctl 看日志

配合第 1 篇别名 `logsvc`:

```bash
# 实时滚动
sudo journalctl -u nginx -f

# 最近 2 小时
sudo journalctl -u nginx --since "2 hours ago"

# 本次启动以来
sudo journalctl -u nginx -b

# 优先级:错误及以上
sudo journalctl -u nginx -p err..alert --since today

# 不分页一次 dump
sudo journalctl -u nginx --no-pager -n 100
多服务同时看:

```bash
sudo journalctl -u nginx -u gunicorn -f
---

## 3. journal 占满磁盘

```bash
journalctl --disk-usage
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=500M
持久化限制(可选):

```bash
sudo mkdir -p /etc/systemd/journald.conf.d  
sudo tee /etc/systemd/journald.conf.d/size.conf << 'EOF'  
[Journal]  
SystemMaxUse=500M  
EOF  
sudo systemctl restart systemd-journald
---

## 4. 最小自定义 service 示例

`/etc/systemd/system/myapp.service`:

```ini
[Unit]
Description=My Python App
After=network.target

[Service]
User=deploy
WorkingDirectory=/var/www/myapp
ExecStart=/var/www/myapp/venv/bin/gunicorn -b 127.0.0.1:8000 wsgi:application
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
启用:

```bash
sudo systemctl daemon-reload  
sudo systemctl enable --now myapp  
sudo journalctl -u myapp -f
---

## 5. 经典 `service` 命令

MySQL 等仍可用:

```bash
sudo systemctl status mysql
sudo systemctl restart mysql
`service mysql restart` 在 systemd 下多为兼容别名。

---

## 6. 应用日志 vs journal

| 来源 | 路径/命令 |
|------|-----------|
| systemd 服务 | `journalctl -u xxx` |
| nginx | `/var/log/nginx/error.log` |
| 通用系统 | `/var/log/syslog` |
| 内核 | `dmesg -T` |

---

## 本篇速查

```bash
sudo systemctl status SERVICE --no-pager  
sudo journalctl -u SERVICE -f  
sudo journalctl --disk-usage && sudo journalctl --vacuum-time=7d

```


系列导航

链接
1–3 /forum/13/ /forum/14/ 磁盘见上篇
4 systemd/journal(本文)
5–8 网络 / 监控 / 诊断 / Cron