乐闻世界logo
搜索文章和话题

How to use systemctl and service commands to manage services in Linux system service management?

2月17日 23:35

Linux system service management is a core skill for operations engineers, mainly involving systemd and traditional init systems.

systemd service management:

  • systemctl start service: start service
  • systemctl stop service: stop service
  • systemctl restart service: restart service
  • systemctl reload service: reload configuration (without interrupting service)
  • systemctl status service: view service status
  • systemctl enable service: set service to start automatically on boot
  • systemctl disable service: cancel service auto-start on boot
  • systemctl is-enabled service: check if service is set to auto-start
  • systemctl list-units --type=service: list all services
  • systemctl list-unit-files --type=service: list all service files
  • systemctl daemon-reload: reload systemd configuration

Service configuration files:

  • Location: /etc/systemd/system/ or /usr/lib/systemd/system/
  • Example: /etc/systemd/system/nginx.service

Service configuration file format:

ini
[Unit] Description=nginx service After=network.target [Service] Type=forking ExecStart=/usr/sbin/nginx ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target

Traditional init service management (SysVinit):

  • service service start: start service
  • service service stop: stop service
  • service service restart: restart service
  • service service status: view service status
  • chkconfig --list: list all services
  • chkconfig service on: set service to start automatically on boot
  • chkconfig service off: cancel service auto-start on boot

Service log management:

  • journalctl -u service: view logs for a specific service
  • journalctl -u service -f: view service logs in real-time
  • journalctl -u service --since today: view today's logs
  • journalctl -u service --since "2024-01-01" --until "2024-01-02": view logs for a specific time period
  • journalctl -p err: view error-level logs
  • /var/log/messages: main system log
  • /var/log/syslog: system log (Debian/Ubuntu)

Service troubleshooting:

  • Check service status: systemctl status service
  • View service logs: journalctl -u service
  • Check configuration file: cat /etc/systemd/system/service.service
  • Check port listening: ss -tulnp | grep service
  • Check process: ps aux | grep service
  • Manual startup test: directly run the service's executable

Service optimization:

  • Adjust startup order: use After and Wants directives
  • Set resource limits: use LimitCPU, LimitMEM and other directives
  • Configure auto-restart: Restart=on-failure, RestartSec=10s
  • Optimize startup time: use Type=simple or Type=notify
标签:Linux