大网数据广告活动
服务器运维问答

Systemd restart service if it's not listening to a port

· 52CE 我爱测

I've been using Systemd for a while in Debian 8. I use the Restart=on-failure option to waken-up a service in case of failure. I will like to know if there is a way to force the restart of the service if it is not listening to a …

问题原文

原帖链接 · Adrian Antunez · CC BY-SA 3.0

I've been using Systemd for a while in Debian 8. I use the Restart=on-failure option to waken-up a service in case of failure.

I will like to know if there is a way to force the restart of the service if it is not listening to a specific port (even if the process stills running).

The reason of why I need that is because we are developing the new feature to will fix this issue but it will require a while. Meanwhile we need a workaround.

I have developed a script to check that status:

#! /bin/bash
PORTS=( 1452 542 )
for port in ${PORTS[@]}; do
    netstat -anp | grep $port > /dev/null 2>&1
    if [ "$?" -ne 0 ]; then
        # Port blocked. Kill the running process and start it again after a while
done

This script is triggered periodically using the cron.I know it is a dirty trick. That's why I would like to integrate that behaviour in Systemd checking. Is that possible?

Thank you in advance.

Cheers,

A.

已采纳解答

原帖链接 · aseq · CC BY-SA 3.0

I would suggest you approach it differently and use a dedicated monitoring tool to accomplish this.

My favourite monitoring tool which allows services to be restarted in case they crash, or are not listening at their configured port(s) anymore is monit: https://packages.debian.org/jessie/monit

There are plenty of examples in the configuration file, on this site and elsewhere about setting it up. I will list an example to give you an idea how simple it is to use, the example uses init.d however it can easily be converted to use systemd.

To test a process exists and is listening on a specific port and to start it when this test fails:

check process example with pidfile /var/run/example.pid
start program = "/etc/init.d/example start"
start program = "/etc/init.d/example stop"
if failed host 192.0.2.10 port 80 protocol http then restart
if 5 restarts within 5 cycles then timeout

You can leave out the protocol http part and monit will do just a simple tcp connect to test it out. The protocol argument does a more involved test to check whether something is actually responding to, for example, an http get request.

You need to make sure the process or service is started in such a way a corresponding pid file is created in /var/run. Monit itself doesn't take care of that. Normally if the service is started through an init script or systemd it should have a pid file in /var/run.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-06-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。