3
3

More than 3 years have passed since last update.

systemctlってめちゃくちゃ便利なんだな...

Posted at

nodeのアプリをforeverでデーモン化しようと思っていたところ、そもそもsystemctl使えば必要なかったという話です。

前提

  • ts-nodeのexpressアプリをデーモン化したい
  • サーバー起動時にも起動したい
  • AWSのEC2

systemctlの設定を書く

systemctlは昔のserviceコマンドに替わるものですがだいぶ便利になっています。

昔はinit.dにややこしい起動スクリプトを書く必要がありましたが今では、

/usr/lib/systemd/system/foo.service
[Unit]
Description=foo

[Service]
Type=simple
ExecStart="/home/ec2-user/repo/script/start.sh"

[Install]
WantedBy=multi-user.target

これだけで

$ sudo systemctl enable foo
$ sudo systemctl start foo
$ sudo systemctl stop foo

できます。

start.shには、普通にyarn startが書かれています。
もちろんパスを通したりする必要はありますが。
こんな感じで書いてます。

start.sh
#!/bin/bash

set -e

cd /home/ec2-user/repo

export PATH=/home/ec2-user/.nvm/versions/node/v14.3.0/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/ec2-user/.local/bin:/home/ec2-user/bin:$PATH

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

/home/ec2-user/.nvm/versions/node/v14.3.0/bin/yarn start

便利な世の中になりましたね。

どうでもいいけどserviceコマンドと違って

$ service foo start
$ systemctl start foo

逆なのがなかなか慣れない...

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3