1. 概要
「Ubuntu 22.04」上に。
/opt/python/bin/python /path/to/main.py
で、動作させているプログラムがありまして。
これをデーモン化する方法について、メモします。
2. サービスの記述
sudo vi /etc/systemd/system/mypython.service
下記を記述します。
[Unit]
Description=My Python Application
After=network.target
[Service]
Type=simple
User=ubuntu
Group=ubuntu
WorkingDirectory=/path/to
ExecStart=/opt/python/bin/python /path/to/main.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
3. 起動・有効化
サービスを再読み込み。
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
起動・有効化。
sudo systemctl start myapp.service
sudo systemctl enable myapp.service
動作確認します。
sudo systemctl status myapp.service
下記のように出力されれば、うまく動作しています。
● myapp.service - My Python Application
Loaded: loaded (/etc/systemd/system/myapp.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2025-12-22 01:40:50 UTC; 21s ago
Main PID: 2190 (python)
Tasks: 3 (limit: 4512)
Memory: 22.0M
CPU: 134ms
CGroup: /system.slice/mqtt-python.service
mq2190 /opt/python/bin/python /path/to/main.py
4. 参考サイト
本ページは、「ChatGPT」軍曹を参考にさせていただきました。