When copying a container /etc/hosts is not copied

Every time I copy a container the /etc/hosts files is reset to a default (lxd?) version.
Why it this? We use extra hardcoded hosts in the /etc/hosts file. Now we need to restore that after copying.

So this is a behaviour of the image metadata templates. These are file templates that are applied when creating a new container (from an image or from an existing container).

Commonly the two files that are regenerated when copying a container are the /etc/hosts file and the /etc/hostname file so that it can be updated with the new container’s host name.

There’s a couple of options to fix this depending on your requirements.

If you are going to be creating lots of containers from this copy and want the /etc/hosts file to be updated to reflect the new hostname of the container, while still leaving the custom hosts entries intact, then I would suggest that you update the template file for the source container.

To do this:

  1. Start the source container so it is mounted. lxc start c1.
  2. Edit the file /var/snap/lxd/common/lxd/containers/c1/templates/hosts.tpl.
  3. Add the custom hosts entries to this file.
  4. Save file and then all copies of that container will include those entries.

The other option is to update the source container’s metadata to instruct it to not replace the /etc/hosts file if it already exists. This will not then update the /etc/hosts file in the copy to reflect the new container’s host name though.

To do this:

  1. Start the source container so it is mounted. lxc start c1.
  2. Edit the file /var/snap/lxd/common/lxd/containers/c1/metadata.yaml.
  3. Find the section for /etc/hosts and set create_only: true.
  4. Save file and then all copies of that container will not change /etc/hosts file (and will have source container’s host name in).
1 Like

Thanks for the info. Only that directories are not mounted after the container is started. Shouldn’t I first do some namespace thing? If I remember correctly I read that somewhere.

I used a dir storage pool in my post above, but if using another storage driver you may need to use nsenter to enter the mount namespace of the lxd when running from the snap package.

sudo nsenter --mount=/run/snapd/ns/lxd.mnt

Thanks for the command. When using lxd on production servers the dir based storage pool is not the best choice :-).

1 Like