How do I get the IP address of an LXC container?

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.


Solution 1:

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

Solution 2:

Seeing as running things in containers doesn't appear to be supported in Ubuntu, my next best suggestion is to look at the IP address leases that dnsmasq is handing out. That's really simple:

$ cat /var/lib/misc/dnsmasq.leases
1363699477 00:16:3e:4a:ce:a4 10.0.3.83 containername *

There are only two parts there that are of any use, so we can format that up a lot nicer:

$ awk '{ print $4,$3 }' /var/lib/misc/dnsmasq.leases | column -t
containername  10.0.3.83