Friday, April 7, 2017

How to check if you're inside a lxc container

The "usual" way of checking whether your process is running inside a lxc container is to look at /proc/1/cgroup. For example:
# cat /proc/1/cgroup
13:name=systemd:/
12:pids:/
11:perf_event:/
10:net_prio:/
9:net_cls:/
8:memory:/
7:hugetlb:/
6:freezer:/
5:devices:/
4:cpuset:/
3:cpuacct:/
2:cpu:/
1:blkio:/

# lxc-attach -n foo -- cat /proc/1/cgroup
13:name=systemd:/lxc/foo
12:pids:/lxc/foo
11:perf_event:/lxc/foo
10:net_prio:/lxc/foo
9:net_cls:/lxc/foo
8:memory:/lxc/foo
7:hugetlb:/lxc/foo
6:freezer:/lxc/foo
5:devices:/lxc/foo
4:cpuset:/lxc/foo
3:cpuacct:/lxc/foo
2:cpu:/lxc/foo
1:blkio:/lxc/foo
Another way to do it is to check the hostid of the system, that requires some knowledge about what the hostid looks on your system but at least provides a programmatic way of doing so (since you can use the gethostid() and sethostid() library calls instead of running a command). For example:
# hostid
ae031411
# lxc-attach -n foo -- hostid
4487013
Note that it is possible that both hostids are the same, so once again, this method relies on some additional knowledge about the system.

No comments:

Post a Comment