如何使用 systemd 在启动时运行单个命令?

mac*_*ey7 164 startup systemd

我想在启动后使用以下命令启动一个 Apache Spark 集群:

sudo ./path/to/spark/sbin/start-all.sh
Run Code Online (Sandbox Code Playgroud)

然后在系统准备重新启动/关闭时运行此命令:

sudo ./path/to/spark/sbin/stop-all.sh
Run Code Online (Sandbox Code Playgroud)

我该如何开始?有我可以建立的基本模板吗?

我试图使用一个非常简单的(文件:)/lib/systemd/system/spark.service

[Unit]
Description=Spark service

[Service]
ExecStart=sudo ./path/to/spark/sbin/start-all.sh
Run Code Online (Sandbox Code Playgroud)

哪个不起作用。

Geo*_*sen 225

您的.service文件应如下所示:

[Unit]
Description=Spark service

[Service]
ExecStart=/path/to/spark/sbin/start-all.sh

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

现在,再执行几个步骤来启用和使用该.service文件:

  1. 将它放在/etc/systemd/system文件夹中,并说出名称myfirst.service

  2. 确保您的脚本可执行:

    chmod u+x /path/to/spark/sbin/start-all.sh
    
    Run Code Online (Sandbox Code Playgroud)
  3. 启动它:

    sudo systemctl start myfirst
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使其在启动时运行:

    sudo systemctl enable myfirst
    
    Run Code Online (Sandbox Code Playgroud)
  5. 停下来:

    sudo systemctl stop myfirst
    
    Run Code Online (Sandbox Code Playgroud)

笔记

  1. 您不需要sudo在您的服务中启动 Spark ,因为默认服务用户已经是 root。

  2. 查看下面的链接以获取更多systemd选项。

而且

现在我们上面的只是基本的,这是一个完整的 spark 设置:

[Unit]
Description=Apache Spark Master and Slave Servers
After=network.target
After=systemd-user-sessions.service
After=network-online.target

[Service]
User=spark
Type=forking
ExecStart=/opt/spark-1.6.1-bin-hadoop2.6/sbin/start-all.sh
ExecStop=/opt/spark-1.6.1-bin-hadoop2.6/sbin/stop-all.sh
TimeoutSec=30
Restart=on-failure
RestartSec=30
StartLimitInterval=350
StartLimitBurst=10

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

要设置服务:

sudo systemctl start spark.service
sudo systemctl stop spark.service
sudo systemctl enable spark.service
Run Code Online (Sandbox Code Playgroud)

进一步阅读

请通读以下链接。Spark 是一个复杂的设置,因此您应该了解它如何与 Ubuntu 的 init 服务集成。


Luc*_*Luc 5

将其复制粘贴到终端(以 root 身份)中以/root/boot.sh在启动时创建和运行它:

bootscript=/root/boot.sh
servicename=customboot

cat > $bootscript <<EOF
#!/usr/bin/env bash
echo "$bootscript ran at \$(date)!" > /tmp/it-works
EOF

chmod +x $bootscript

cat > /etc/systemd/system/$servicename.service <<EOF
[Service]
ExecStart=$bootscript
[Install]
WantedBy=default.target
EOF

systemctl enable $servicename
Run Code Online (Sandbox Code Playgroud)

要修改参数,例如使用不同的$bootscript,只需手动设置该变量并在复制命令时跳过该行。

运行命令后,您可以/root/boot.sh使用您喜欢的编辑器进行编辑,它将在下次启动时运行。您还可以使用以下命令立即运行它:

systemctl start $servicename
Run Code Online (Sandbox Code Playgroud)