一、为什么用 Systemd

在 Linux 服务器上部署 Java 应用时,直接用 java -jar 启动会有几个问题:终端关闭后进程退出、服务器重启后需要手动启动、异常崩溃后无法自动恢复。Systemd 是现代 Linux 的默认 init 系统,可以优雅地解决这些问题。

二、编写 Service 单元文件

假设有一个 Java 监控应用 Notpad.jar,部署在 /opt/Notpad/ 目录下,需要监听 4000 端口。

创建服务文件:

sudo vim /etc/systemd/system/Notpad.service

写入以下内容:

[Unit]
Description=Notpad Monitor Service
Documentation=https://caadb.cc
After=network.target

[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/Notpad
ExecStart=/usr/bin/java -jar /opt/Notpad/Notpad.jar --server.port=4000
ExecStop=/bin/kill -TERM $MAINPID
Restart=always
RestartSec=10
StandardOutput=append:/var/log/Notpad/app.log
StandardError=append:/var/log/Notpad/error.log

[Install]
WantedBy=multi-user.target

三、配置项详解

[Unit] 部分

  • Description:服务描述信息
  • After=network.target:在网络服务启动后再启动本服务

[Service] 部分

  • Type=simple:最常用的类型,ExecStart 启动的进程就是主进程
  • User=appuser:以非 root 用户运行,提高安全性
  • WorkingDirectory:设置工作目录
  • ExecStart:启动命令
  • Restart=always:无论什么原因退出都自动重启
  • RestartSec=10:重启前等待 10 秒,避免频繁重启
  • StandardOutput / StandardError:日志输出到文件

[Install] 部分

  • WantedBy=multi-user.target:在多用户模式下启用,即开机自启

四、常用管理命令

# 重新加载 systemd 配置(修改 service 文件后必须执行)
sudo systemctl daemon-reload

# 启动服务
sudo systemctl start Notpad

# 停止服务
sudo systemctl stop Notpad

# 重启服务
sudo systemctl restart Notpad

# 查看状态
sudo systemctl status Notpad

# 设置开机自启
sudo systemctl enable Notpad

# 取消开机自启
sudo systemctl disable Notpad

# 查看实时日志
sudo journalctl -u Notpad -f
提示:修改 service 文件后,必须先执行 systemctl daemon-reload,否则 systemd 不会读取到最新的配置。

五、日志管理

上面配置中将日志输出到了文件。如果希望使用 systemd 自带的日志系统(journald),可以去掉 StandardOutputStandardError 行,然后使用 journalctl 查看日志:

# 查看最近 100 行日志
sudo journalctl -u Notpad -n 100

# 查看今天的日志
sudo journalctl -u Notpad --since today

# 实时跟踪日志
sudo journalctl -u Notpad -f

六、总结

使用 Systemd 管理 Java 服务是一种简单、可靠的方式。通过配置 Restart=always 可以实现崩溃自动恢复,通过 enable 可以实现开机自启。相比传统的 nohupscreen 方式,Systemd 提供了更完善的进程管理、日志收集和依赖控制能力,是生产环境部署的推荐方案。