Set lifetime of a container

Hi,

Is there a way to limit the lifetime of a container? E.g. auto delete after 7 days.

Thanks.

You can use the --ephemeral flag when you create a container so that once you stop it, the container is automatically deleted. For example,

lxc launch ubuntu: mycontainer --ephemeral

Then, if you stop it, it gets deleted.

lxc stop mycontainer

I am not aware of a built-in mechanism in LXD to autodelete a container.

1 Like

Thanks but my question was more about setting a time limit than auto deleting.

The short answer is no.
Also, I am not a LXD maintainer.

LXD has a feature to automatically create snapshots of a container, and then autoexpire them after a specified interval. Such a feature is good, and helps to retain, let’s say, the last 7 daily snapshots.
Because older snapshots are important any more, and having 7 daily snapshots gives you 7 days of breathing space to fix a disaster.
But even if LXD did not have this feature, it would be possible to create a set of external scripts to implement it. There was a good use-case to have LXD implement this and it was implemented.
In a tool like LXD, new features tend to be more conservative than not.

Currently, there is no autodelete a container after an interval in LXD.
To have such a mechanism in LXD, there should be a justification for the general use by many of the users. Can you describe a use-case that such a feature would be useful?

Thanks for you answer.
My use case:
I am building a lab environment using LXD where a user/student should be able to spin up 1 or more predefined containers but only for a fixed duration (after which it should be auto-deleted).

It would be nice to be able to start a container with a time limit option so it stops after xx time.
I guess that for the moment I will have to script this.

Have a look at https://github.com/lxc/lxd-demo-server (live demo at https://linuxcontainers.org/lxd/try-it/).
The containers are autodeleted in 30 minutes, and that is implemented on top of LXD.
It might fit in your use-case.

1 Like

Yeah, this isn’t really something we’ve had any request for before but would be trivial for you to implement with a script as the API exposes the creation time on all containers.

How about creating a Python script (using pylxd) and maintained by systemd which monitors the containers… and then when the lifetime is up stops and deletes them…

If your host has systemd installed, you could perhaps delay the shutdown of an --ephemeral container in an ad-hoc fashion.

Look at the help for systemd-run with systemd-run --help, and look at the timer options.