在使用Ubuntu或其它基于Debian的Linux系统时,你可能会遇到需要让某个程序在系统启动时自动运行的情况。这时候,Ubuntu init.d脚本就派上用场了。本文将从零开始,详细讲解如何编写一个标准的init.d脚本,即使是Linux新手也能轻松掌握。
/etc/init.d/ 是传统SysV init系统中存放系统服务启动脚本的目录。虽然现代Ubuntu版本(15.04以后)默认使用systemd,但为了兼容性,init.d仍然被广泛支持。通过编写符合规范的init.d脚本,你可以轻松管理自定义服务的启动、停止和重启。
一个标准的init.d脚本通常包含以下要素:
假设你有一个Python编写的简单Web应用 /opt/myapp/app.py,现在我们要为它创建一个init.d脚本。
使用root权限在 /etc/init.d/ 目录下创建新脚本:
sudo nano /etc/init.d/mywebapp
将以下内容复制到文件中:
#!/bin/bash### BEGIN INIT INFO# Provides: mywebapp# Required-Start: $local_fs $network $named $time $syslog# Required-Stop: $local_fs $network $named $time $syslog# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Description: My Custom Web Application Service### END INIT INFO# 脚本路径和名称DAEMON=/usr/bin/python3DAEMON_ARGS="/opt/myapp/app.py"NAME=mywebappPIDFILE=/var/run/$NAME.pidSCRIPTNAME=/etc/init.d/$NAME# Exit if the package is not installed[ -x "$DAEMON" ] || exit 0# Read configuration variable file if it is present[ -r /etc/default/$NAME ] && . /etc/default/$NAME# Load the VERBOSE setting and other rcS variables. /lib/init/vars.sh# Define LSB log_* functions.. /lib/lsb/init-functions## Function that starts the daemon/service#do_start(){ start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON \ --background --make-pidfile --chuid nobody --startas $DAEMON \ -- $DAEMON_ARGS}## Function that stops the daemon/service#do_stop(){ start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE rm -f $PIDFILE}case "$1" in start) log_daemon_msg "Starting system $NAME daemon" do_start log_end_msg $? ;; stop) log_daemon_msg "Stopping system $NAME daemon" do_stop log_end_msg $? ;; restart|force-reload) log_daemon_msg "Restarting system $NAME daemon" do_stop sleep 2 do_start log_end_msg $? ;; status) status_of_proc -p $PIDFILE "$DAEMON" "$NAME" && exit 0 || exit $? ;; *) echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload|status}" >&2 exit 3 ;;esac 确保脚本具有可执行权限:
sudo chmod +x /etc/init.d/mywebapp
使用update-rc.d命令将服务加入启动项:
sudo update-rc.d mywebapp defaults
现在可以测试你的服务了:
sudo service mywebapp startsudo service mywebapp statussudo service mywebapp stop
在上面的脚本中,有几个关键部分需要特别注意:
log_daemon_msg和log_end_msg提供统一的日志输出格式。在编写和使用Ubuntu init.d脚本时,可能会遇到以下问题:
--chuid参数指定运行用户,避免以root身份运行应用。虽然init.d脚本仍然有效,但建议在较新的Ubuntu版本中使用systemd服务单元文件,它提供了更强大的功能和更好的性能。不过,了解init.d对于维护旧系统或需要兼容性的场景仍然非常重要。
通过本教程,你应该已经掌握了如何编写一个完整的Ubuntu init.d脚本。无论是为了Linux系统启动脚本的学习,还是实际的Ubuntu服务管理需求,这些知识都能帮助你更好地控制系统的启动行为。记住,良好的脚本应该包含完整的错误处理、清晰的日志输出和正确的权限设置。
希望这篇编写init.d脚本教程对你有所帮助!如果你有任何问题或建议,欢迎在评论区留言讨论。
本文由主机测评网于2025-12-16发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025128679.html