skip to Main Content

last reboot works in a linux machine

$ last reboot
reboot   system boot  4.15.0-142-gener Thu May 11 16:31   still running
...

wtmp begins Fri May  5 19:27:11 2023

Inside a container, it doesn’t (returns empty)

# last reboot

wtmp begins Mon Mar 27 09:55:22 2023

Is there a way to know the uptime/last-reboot of the host machine from inside a container?

2

Answers


  1. last reads the boot times from /var/log/wtmp, so if you map that file into the container, it’ll show the boot times of the host. Like this

    docker run --rm -v /var/log/wtmp:/var/log/wtmp:ro debian last reboot
    
    Login or Signup to reply.
  2. last(1) looks in the file /var/log/wtmp for this information. Since the container has its own isolated filesystem, it can’t see the host’s wtmp file, and this information is not accessible.

    procinfo(8) includes this information from the artificial /proc filesystem. Since this is kernel-level data you should be able to read it.

    More specifically, proc(5) documents that /proc/uptime contains the time the system has been running in seconds. You can subtract that from the current time to find the last time the system has been rebooted.

    cat /proc/uptime
    675814.56 1014657.89
    

    This fragment should work on most Linux environments (the date -d option is not specified by POSIX, but this works in both busybox and ubuntu containers):

    #!/bin/sh
    now=$(date +%s)
    uptime=$(cut -d. -f1 /proc/uptime) # cut on the decimal point, so in whole seconds
    boot_time=$(("$now" - "$uptime"))
    date -d "$boot_time"
    

    Note though, if your Docker is running in a virtual machine (including Docker Desktop on all platforms) this returns the boot time of the VM and not of the containing host.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search