brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: systemd-detect-virt tells a script whether it runs in a VM or container

Systemd
~/tips/tip-systemd-detect-virt

systemd-detect-virt

Let a script check if it is on bare metal, in a VM or inside a container.

Some setup scripts should behave differently on a physical box than in a VM or container: skip the disk spin down, skip SMART checks, skip setting the hardware clock.

Run it without options and it prints what it found:

systemd-detect-virt
systemd-detect-virt --container
systemd-detect-virt --vm

Inside a Docker container it prints docker. Other answers are names like kvm, vmware, microsoft, lxc or wsl, and none on bare metal. --container and --vm limit the check to one kind, which matters for a container running inside a VM.

For scripts, use the exit code with -q. It returns 0 when it detects virtualization and non-zero when it does not:

if systemd-detect-virt -q --vm; then
  echo "in a VM, skipping smartctl"
else
  smartctl -H /dev/sda
fi

In units you do not need the command at all; ConditionVirtualization= does the same check.

Detection relies on hints the hypervisor or container runtime leaves behind, such as CPU flags, DMI data and files like /.dockerenv. Unusual setups can hide or fake those hints, so I would not use it as a security check.

Further reading: systemd-detect-virt man page

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass – dbpass.cred systemd-analyze timespan 1h30min All Systemd tips (88) All topics

Link