How to Get the IP Address of an LXC Container

12.04lxc

I've written a few scripts to manage LXC containers, and I can get their IP addresses via ifconfig, assuming I'm connected to the console.

I now want to connect to these containers via ssh. How do I get their IP address in such a way that I can write a script? I also don't want to set the addresses manually (but I'll do it, if that's the only option).

So far, I've tried using lxc-start, but the machine doesn't have an IP address before I run /sbin/init.

Best Answer

The easiest way to do this now is:

lxc-info -n container-name -iH

This returns the IP address with no other text.

The -i option specifies that the IP address should be returned and the -H option disables human readable output i.e. labels. For more info see the lxc-info man page.

EDIT for newer version of LXC:

lxc info container-name

Then you get detailed info. Look at the "Ips:" block, which should look like the one below. You might one to grab the first IPv4 address (10.121.48.241) in this case:

Ips:
  eth0: inet    10.121.48.241   vethSBP4RR
  eth0: inet6   fda5:b9a9:f3b9:ba32:216:3eff:fe4a:4d7d  vethSBP4RR
  eth0: inet6   fe80::216:3eff:fe4a:4d7d    vethSBP4RR
  lo:   inet    127.0.0.1
  lo:   inet6   ::1