#6 of 11Deploying Python FastAPI & Django with Systemd
IntermediateDeployment⏱️ 10 min

Deploying Python FastAPI & Django with Systemd

Python FastAPI နှင့် Django ကို Linux Systemd Daemon ဖြင့် တင်နည်း

Set up Python virtual environments, Gunicorn, Uvicorn ASGI workers, and create native Linux Systemd service units.

Python Web App များကို Virtual Environment, Uvicorn, Gunicorn တို့ဖြင့် စီမံပြီး Linux ၏ Native Systemd Service အဖြစ် အမြဲတမ်း run ထားနည်း။

1. Create Systemd Service Unit (Linux Native Daemon)

/etc/systemd/system/ တွင် Service ဖိုင် ရေးသားခြင်း

Linux OS ၏ ကျောရိုးဖြစ်သော Systemd သည် Background Services များကို စီမံခန့်ခွဲရာတွင် အလုံခြုံဆုံးနှင့် အားအထားရဆုံး စနစ် ဖြစ်ပါသည်။ Python FastAPI app အတွက် သီးသန့် Service တစ်ခုကို ဖန်တီးပေးရပါမည်။

/etc/systemd/system/fastapi.service
ini
1 $ [Unit]
2 $ Description=FastAPI Application Daemon
3 $ After=network.target
4 $
5 $ [Service]
6 $ User=deployer
7 $ Group=deployer
8 $ WorkingDirectory=/home/deployer/my-fastapi-app
9 $ Environment="PATH=/home/deployer/my-fastapi-app/venv/bin"
10 $ ExecStart=/home/deployer/my-fastapi-app/venv/bin/gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 127.0.0.1:8000
11 $ Restart=always
12 $ RestartSec=5
13 $
14 $ [Install]
15 $ WantedBy=multi-user.target
💡Command ရှင်းလင်းချက် (ဖတ်ရှုရန် နှိပ်ပါ)

Systemd သည် deployer user အခွင့်အရေးဖြင့် virtual environment ထဲရှိ Gunicorn/Uvicorn worker ၄ ခုကို run ပေးပြီး app crash ဖြစ်သွားပါက ၅ စက္ကန့်အကြာတွင် အလိုအလျောက် ပြန်စတင်ပေးမည် ဖြစ်ပါသည်။

Manage Systemd Service via systemctl
bash
1 $ # Reload systemd to detect new service
2 $ sudo systemctl daemon-reload
3 $
4 $ # Start and enable on boot
5 $ sudo systemctl start fastapi
6 $ sudo systemctl enable fastapi
7 $
8 $ # Check service status and logs
9 $ sudo systemctl status fastapi
10 $ sudo journalctl -u fastapi -f
💡Command ရှင်းလင်းချက် (ဖတ်ရှုရန် နှိပ်ပါ)

journalctl -u fastapi -f command ဖြင့် Python app ထဲမှ print ထုတ်သမျှ error log များကို အချိန်နှင့်တပြေးညီ live ကြည့်ရှုနိုင်ပါသည်။

Knowledge Check

Which command must you run to reload Systemd manager configuration after creating or editing a .service file?

/etc/systemd/system/ တွင် service unit ဖိုင်အသစ် ဖန်တီးပြီးပါက systemd daemon အား အပြောင်းအလဲ သိရှိစေရန် မည်သည့် command ကို မဖြစ်မနေ run ရသလဲ?