Systemd, IP 주소가 변경되면 서비스 다시 시작

Systemd, IP 주소가 변경되면 서비스 다시 시작

나는 매우 간단한 서비스를 작성했습니다.

[Unit]
Description=Service on interface %I

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/lib/project/my_script.sh start %I

[Install]
WantedBy=multi-user.target

내가 시작하는 것은 네트워크 인터페이스가 systemclt start myservice@net0어디에 있는지입니다. net0네트워크 인터페이스가 다시 시작될 때마다 서비스를 다시 시작하려면 어떻게 해야 합니까?

답변1

다음과 같이 시스템 장치가 해당 인터페이스에 대해 해당 네트워크 인터페이스(자동으로 로드됨)에 대한 장치를 바인드( BindTo)하고 의존( DependsOn) 하도록 할 수 있습니다 ..device

[Unit]
Description=Service on interface %I
BindsTo=sys-subsystem-net-devices-%i.device
After=sys-subsystem-net-devices-%i.device

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/lib/project/my_script.sh start %I

[Install]
WantedBy=multi-user.target

사용자 정의 장치에 네트워크 인터페이스가 필요한 경우 Wants추가 하여 장치의 종속성을 공식화하기를 원할 것입니다.After실제로 온라인섹션 에 다음을 추가하여 [Unit]:

Wants=network-online.target
After=network-online.target

주의: 다음을 수행하여 .device단위가 맞는지 확인할 수 있습니다 .loadedsystemctl list-units --type=device

답변2

아마도 이것이 효과가 있을 것입니다:https://clinta.github.io/run-service-on-ip-change/

# /etc/systemd/system/ip-change-mon.service

[Unit]
Description=IP Change Monitor
Wants=network.target
After=network-online.target

[Service]
ExecStart=:/bin/bash -c "ip mon addr | sed -nu -r
\'s/.*[[:digit:]]+:[[:space:]]+([^[:space:]]+).*/\\1/p\' | while read iface; do
systemctl restart ip-changed@${iface}.target; done"

[Install]
WantedBy=multi-user.target default.target

관련 정보