본문 바로가기
Programing/Linux

Linux에서 Systemd 서비스를 만드는 방법

by 멍멍돌이야 2022. 6. 4.
반응형

때때로 스크립트를 만든 다음 systemd에서 스크립트를 제어하도록 하거나 어떤 경우에는 스크립트가 어떤 이유로 종료될 때 스크립트가 스스로 다시 시작되기를 원할 수 있습니다. 이러한 경우 Linux의 systemd는 관리할 수 있는 서비스를 구성하는 데 도움이 됩니다. 이렇게 하려면 다음 단계를 따르십시오.

 

 

  1. cd /etc/systemd/system
  2. your-service.service라는 파일을 만들고 다음을 포함합니다. 새 서비스를 포함하려면 서비스 파일을 다시 로드하십시오.

 

[Unit]
Description=<description about this service>

[Service]
User=<user e.g. root>
WorkingDirectory=<directory_of_script e.g. /root>
ExecStart=<script which needs to be executed>
Restart=always

[Install]
WantedBy=multi-user.target

 

가상 환경을 포함하는 Python 특정 프로젝트의 경우:

[Unit]
Description=<project description>

[Service]
User=<user e.g. root>
WorkingDirectory=<path to your project directory containing your python script>
ExecStart=/home/user/.virtualenv/bin/python main.py
Restart=always
# replace /home/user/.virtualenv/bin/python with your virtualenv and main.py with your script

[Install]
WantedBy=multi-user.target

또는

[Unit]
Description=<project description>

[Service]
User=<user e.g. root>
WorkingDirectory=<path to your project directory>
ExecStart=/bin/bash -c 'cd /home/ubuntu/project/ && source venv/bin/activate && python test.py'

[Install]
WantedBy=multi-user.target

 

 

 



  •  
  • Reload the service files to include the new service.
    sudo systemctl daemon-reload


  • Start your service
    sudo systemctl start your-service.service

  • To check the status of your service
    sudo systemctl status example.service

  • To enable your service on every reboot
    sudo systemctl enable example.service

  • To disable your service on every reboot
    sudo systemctl disable example.service

 

 

 

 

vi /etc/systemd/system/postgres.service
[Unit] 
Description=PostgreSQL server 
After=network.target
  
[Service] 
Type=forking
  
User=postgres 
Group=postgres 
Environment=PGSTARTTIMEOUT=270 
Environment=PGDATA=/data/jaedo/postgres-data 
ExecStart=/data/jaedo/postgres/bin/pg_ctl -D ${PGDATA} -l /data/jaedo/postgres/logs/postgres.log start 
ExecStop=/data/jaedo/postgres/bin/pg_ctl -D ${PGDATA} -l /data/jaedo/postgres/logs/postgres.log stop 
ExecReload=/data/jaedo/postgres/bin/pg_ctl -D ${PGDATA} -l /data/jaedo/postgres/logs/postgres.log reload 
TimeoutSec=300 
[Install] 
WantedBy=multi-user.target

 

systemctl daemon-reload
systemctl enable postgres.service
systemctl start postgres.service
systemctl  stop postgres.service
728x90
반응형

댓글