I use LXC containers on my laptop for testing purpose quite a lot. I create, I destroy, I recreate. LXC is easy to use for this purpose, but one thing was missing on my setup: the automatic creation of a DNS record.
The lxc-net script used on Ubuntu to create the default lxcbr0 bridge provides almost everything to make this possible without too much effort.
The steps to set this up are:
Update /etc/default/lxc-net to define a domain. This domain will be managed by the same dnsmasq process that already serves as DHCP server for the LXC containers.
USE_LXC_BRIDGE="true" LXC_BRIDGE="lxcbr0" LXC_ADDR="10.0.3.1" LXC_NETMASK="255.255.255.0" LXC_NETWORK="10.0.3.0/24" LXC_DHCP_RANGE="10.0.3.2,10.0.3.254" LXC_DHCP_MAX="253" # This is the domain name definition LXC_DOMAIN="lxc"
Restart the service:
$ sudo service lxc-net restart
Validate that the dnsmasq process can resolve a running container IP:
$ dig @10.0.3.1 container_name.lxc ... ;; ANSWER SECTION: container_name.lxc. 0 IN A 10.0.3.156 ...
A nice bonus is that the dns configuration inside a newly started container allows short name resolution:
$ sudo lxc-start -n other_container $ sleep 10 $ sudo lxc-attach -n other_container -- ping -c 2 container_name PING container_name (10.0.3.220) 56(84) bytes of data. 64 bytes from container_name.lxc (10.0.3.220): icmp_seq=1 ttl=64 time=0.039 ms 64 bytes from container_name.lxc (10.0.3.220): icmp_seq=2 ttl=64 time=0.046 ms
To make this setup really usable the host must be configured to redirect DNS queries to the LXC-related dnsmasq process. By default Ubuntu configures /etc/resolv.conf to use 127.0.1.1 as DNS resolver. A dnsmasq process takes care of forwarding the requests to the proper authoritative DNS.
To setup the forwarding, add the following line to /etc/dnsmasq.d/lxc:
If you're running a desktop version of Ubuntu, you probably use Network Manager. Symlink this configuration file to /etc/NetworkManager/dnsmasq.d/lxc and restart Network Manager:
$ sudo ln -s /etc/dnsmasq.d/lxc /etc/NetworkManager/dnsmasq.d/ $ sudo service network-manager restart
DNS resolution should now work on your host:
$ dig container_name.lxc ... ;; ANSWER SECTION: container_name.lxc. 0 IN A 10.0.3.156 ...