[lxc-users] short question: can a user know he is inside a container ?

Leonid Isaev lisaev at umail.iu.edu
Wed Dec 25 21:23:53 UTC 2013


On Wed, 25 Dec 2013 21:52:10 +0100
Stéphane Graber <stgraber at ubuntu.com> wrote:

> On Wed, Dec 25, 2013 at 10:44:21PM +0200, David Shwatrz wrote:
> > Hello, lxc users,
> > 
> > Is there a way for a user who is inside some shell in a container
> > to know that he is inside a container? I am not talking about setting
> > specific different host names to containers, but the question is: is
> > there something general/inherent to containers,  which indicates that
> > a user is  inside a container ?
> > 
> > Best,
> > DavidS
> 
> Yes, there are a few ways to do so.
> 
> If on Ubuntu, the easiest way is to call "running-in-container" which
> will return 0 if you are and 1 if you're not.
> On Ubuntu you can then read /run/container_type to know what technology
> is used (we detect lxc, libvirt-lxc, openvz and vserver).
> 
> If not on Ubuntu, you can basically use the same trick we use on Ubuntu
> to detect containers which is roughly:
> 
> cat /proc/1/environ | tr '\0' '\n' | grep ^container
> 
> Which wiill return "container=lxc" in a LXC container. For other
> container types we need a few more tricks, here are the ones we
> currently use:
> 
>     # Detect old-style libvirt
>     if [ -z "$container" ]; then
>         [ -n "$LIBVIRT_LXC_UUID" ] && container=lxc-libvirt
>     fi
> 
>     # Detect OpenVZ containers
>     if [ -z "$container" ]; then
>         [ -d /proc/vz ] && [ ! -d /proc/bc ] && container=openvz
>     fi
> 
>     # Detect vserver
>     if [ -z "$container" ]; then
>         VXID="$(cat /proc/self/status | grep ^VxID | cut -f2)" || true
>         [ "${VXID:-0}" -gt 1 ] && container=vserver
>     fi
> 
> 
> Between the container env variable and those, you should be able to
> detect pretty much all kind of containers (unless they are tweaked to
> hide those information from you).
> 

To add to this, inside a systemd-based container (fedora, suse, etc) one can
also use systemd-detect-virt(1) (notice the return values):
* On the host
$ systemd-detect-virt; echo $?
none
1
* Inside the (not libvirt) LXC guest
>>> systemd-detect-virt; echo $?
lxc
0

Best,
-- 
Leonid Isaev
GnuPG key: 0x164B5A6D
Fingerprint: C0DF 20D0 C075 C3F1 E1BE  775A A7AE F6CB 164B 5A6D
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-users/attachments/20131225/591157fa/attachment.pgp>


More information about the lxc-users mailing list