How can I overlayfs the root filesystem on linux?

9.5k Views Asked by At

I'm using overlayFS to create a sort of simple experimental sandboxing. I think I understand how it works:

  • lower layer should be always mounted R/O
  • upper layer is where all changes happen
  • work layer is for transactional reasons
  • target is where all merged lower + upper go

As example, I have a physical disk mounted on /disk2. Then I want to overlay to preserve the contents, so I can do something like:

mount("overlay", "/disk2", "overlay", MS_MGC_VAL, "lowerdir=/disk2,upperdir=./upper,workdir=./work");

This works just fine: when my new process tries to amend content under /disk2, then it will only amend in reality under upper: this is indeed working as intended. For example, I can also see the 0, 0 files to show that something is deleted in the upper but not in the lower.

Unfortunately looks like I can't somehow overlay on root /: if I execute the following code:

mount("overlay", "/", "overlay", MS_MGC_VAL, "lowerdir=/disk2,upperdir=./upper,workdir=./work")

I can still see the whole real / and when I write files, they get written in their real (i.e. lower) location, not in the upper one.

What am I doing wrong here?

I am on kernel 4.4.0-53.

2

There are 2 best solutions below

0
Emanuele On BEST ANSWER

According to what I've read I don't think it's possible to programmatically do this once the system is started.

1
1pf1 On

prior-art: If you like one, then this is not for you...

ex. ...previous / partition: /dev/nvme3n2

save your root partition to an image file (ie... dd if=/dev/nvme3n2 of=/free_2_be/2022-12-11-awesome.im bs=44M oflag=direct status=progress)

mount the overlay filesystem to '/' (REALLY not necessary in init *(1) ); then initiate pivot_root ...glory.

** realize that you can never go back if you choose switch_root ...now, don't not never say that nobody didn't provide you with a disclaimer. In regard to the site's privacy policy and whatnot: viking created the word 'law' **

*(1) derived inference from a retrospective regarding that kind of overlay in init, indicates that that kind of thing, in that circumstance, is a problem.