1

I have an application (Django) running in a docker container on a cloud provider. For various reasons it would be useful for me to know when the host itself rebooted, and to save this event somewhere e.g. a database. Obviously it's easy to detect when the application itself starts, but this could have been caused by something other than host reboot. I could in theory catch SIGTERM but again this doesn't necessarily mean a host reboot.

As usual while writing this question I've realised that I could just call uptime and pass through /proc/uptime if necessary, but is this the best way?

eggbert
  • 3,105
  • 5
  • 30
  • 39

2 Answers2

1

There's no need to pass through /proc/uptime, it should already be available inside the container and isn't namespaced or isolated:

$ cat /proc/uptime 
1545872.40 11868963.08

$ docker run -it --rm alpine cat /proc/uptime
1545882.60 11869040.00
BMitch
  • 231,797
  • 42
  • 475
  • 450
0
import time
import subprocess

def uptime():
    res = subprocess.check_output(
        # %Y is last data modification since Epoch
        # proc/1 is the first process started in docker, PID 1
        "stat --format=%Y -t /proc/1/cmdline",
        shell=True,
    )
    uptime_seconds_epoch = int(res.decode().strip())
    now_epoch = int(time.time())
    uptime_seconds = now_epoch - uptime_seconds_epoch
    
    return uptime_seconds
Komu
  • 14,174
  • 2
  • 28
  • 22