Linux从入门到精通Linux服务(如Nginx、MySQL)如何通过`systemd`管理启动、停止和开机自启?

作者:IT技术圈子 阅读:0 日期:2025年09月30日

在Linux系统中,`systemd`是主流的初始化系统和服务管理器,用于管理服务的启动、停止、重启及开机自启。以下是针对Nginx和MySQL等服务的详细操作指南:

# 停止Nginx sudo systemctl stop nginx

# 重启Nginx(修改配置后常用) sudo systemctl restart nginx

# 查看状态 sudo systemctl status nginx ```

开机自启 ```bash # 启用开机自启 sudo systemctl enable nginx

# 禁用开机自启 sudo systemctl disable nginx ```

验证配置 检查Nginx配置语法:`sudo nginx -t` 查看监听端口:`sudo ss -tulnp | grep nginx`

# 停止MySQL sudo systemctl stop mysql

# 重启MySQL sudo systemctl restart mysql

# 查看状态 sudo systemctl status mysql ```

开机自启 ```bash # 启用开机自启 sudo systemctl enable mysql

# 禁用开机自启 sudo systemctl disable mysql ```

安全配置 运行安全脚本(MySQL首次安装后): ```bash sudo mysql_secure_installation ``` 查看日志:`sudo journalctl -u mysql -f`

[Service] Type=simple User=myuser WorkingDirectory=/path/to/app ExecStart=/path/to/app/executable --arg1 --arg2 Restart=on-failure

[Install] WantedBy=multi-user.target ```

操作步骤 1. 创建文件:`sudo nano /etc/systemd/system/myservice.service` 2. 写入配置后保存。 3. 重新加载配置:`sudo systemctl daemon-reload` 4. 启动服务:`sudo systemctl start myservice` 5. 启用开机自启:`sudo systemctl enable myservice`

  • 端口冲突: ```bash sudo ss -tulnp | grep <端口号> ```
  • 权限问题: 确保服务用户(如`mysql`、`nginx`)对相关文件有权限。 检查SELinux/AppArmor是否阻止访问。
  • 通过`systemd`管理服务可以高效地控制生命周期,结合日志和状态检查能快速定位问题。对于生产环境,建议进一步配置日志轮转(`logrotate`)和资源限制(`LimitCPU`、`LimitMEMORY`等参数)。

      END