How to clean up nix containers?

I defined a declarative container in my configuration.nix, then delete its definition. But its data is still there (I learned that when I create another container with the same name). nixos-container destroy container doesn’t say anything and I had to manually do sudo rm -rf /var/lib/containers/{that-name}.
The command results in rm: cannot remove '/var/lib/containers/{that-name}/var/empty': Operation not permitted but at least other unwanted data is cleaned.

Did I miss anything when trying to clean up the old container data? Also, why can’t I delete that /var/empty directory?

The immutable flag is set for /var/empty. You can clear it in order to delete it:

$ sudo chattr -i /var/lib/containers/$container/var/empty
$ sudo rmdir  /var/lib/containers/$container/var/empty
3 Likes

thanks. Do you have any idea about the command nixos-container destroy?

Old thread but I had this problem and have a workaround, that I found from reading the code.

Make a backup of the /etc/containers/$name.conf file. Remove the container from your NixOS configuration and then nixos-rebuild switch. Restore the file you backed up and now you can run “nixos-container destroy $name” to actually remove everything.