LXD share folder from host to container

Problem

Share folder from host to container is easy, just run

lxc config device add <container> <device name> disk source=/path/on/host path=path/in/container

but if you run

lxc launch ubuntu: testbox
lxc config device add testbox share disk source=/home/ubuntu/projects path=/home/zhenkyle/projects

now, you will be disappointed, inside container:

  • Shared file seems to be owned by nobody:nogroup
  • Even using root, touch /home/ubuntu/projects/message will get Permission denied.

Reason

The reason behind this is: in default unprivileged LXC containers, root is maped to one of the subuids of lxd user on host.

You can check it with:

$ cat /etc/subuid
zhenkyle:100000:65536
jargyle:165536:65536
lxd:231072:65536
root:231072:65536

on host

231072 is one of the container's root uid on my host.

In order to solve this problem, you need the technique of map id between host and container.

Solve

As mentioned in Mounting your home directory in LXD, you can do it very easily in unprivileged containers:

# get uid &  gid first
$ id
uid=1000(tycho) gid=1000(zhenkyle)

# set subuid, subgid root can use, the last "1" means only "1000", not a range.
$ echo 'root:1000:1' | sudo tee -a /etc/subuid /etc/subgid

# Creating zesty
$ lxc init ubuntu: zesty

# Key command to do id mapping
$ lxc config set zesty raw.idmap 'both 1000 1000'

# Finally, set up your home directory to be mounted in the container:
$ lxc config device add zesty homedir disk source=/home/ubuntu/projects path=/home/zhenkyle/projects

Now, in lxd container:

  • ubuntu user (uid 1000) will be maped to zhenkyle (1000) user of the host.

  • root user will still be maped to uid 231072 on the host.

Enjoy hacking with LXD.

Reference