AWS
在AWS 创建EC2阶段(可以是Red Hat系统),可以使用如下一段脚本,使得当EC2开机后,为系统添加一个静态网页。
#!/bin/bash
yum install httpd -y
yum update -y
service httpd start
chkconfig httpd on
echo "<html><h1>You are AWSome!!</h1></html>" > /var/www/html/index.html
Raspberry Pi
下文用于和以上对比使用,原文来自于:
Linux 下使用 systemd 设置开机启动项
https://shumeipai.nxez.com/2020/06/30/linux-usage-systemd.html
下面的教程将介绍如何将命令或程序配置为开机启动时自动运行的服务。完成配置之后,就可以通过 Linux 命令行来「启动/停止/禁用」这个服务了。
创建服务
在树莓派上创建一个 .service 文件。例如:
myscript.service
[Unit]
Description=My service
After=network.target
[Service]
ExecStart=/usr/bin/python3 -u main.py
WorkingDirectory=/home/pi/myscript
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target
在上面的范例中,服务会去以 Python 3 来运行 /home/pi/myscript 目录下面的 main.py 脚本。用这种方法,你不仅可以配置 Python 脚本,只需要将 ExecStart 这行改为需要启动的任何程序或脚本即可。
将这个文件用 root 用户保存到 /etc/systemd/system 目录:
sudo cp myscript.service /etc/systemd/system/myscript.service
然后就可以用下面的命令尝试启动服务了:
sudo systemctl start myscript.service
停止服务:
sudo systemctl stop myscript.service
设置开机时自动运行:
sudo systemctl enable myscript.service
systemctl
命令还可以用来重启或禁用它。
注意事项:
1、启动顺序取决于他们的依赖关系。如果是依赖于网络的服务,应当在引导过程中尽可能晚一点启动。
使用 man systemctl
命令或访问 https://fedoramagazine.org/what-is-an-init-system/ 了解更多。