Home > Blockchain >  Use case for excluding --rm flag when running a container
Use case for excluding --rm flag when running a container

Time:01-17

docker container includes an optional --rm flag that has the following description:

Automatically remove the container when it exits

So, including --rm will delete the container after it is stopped. Excluding the flag will keep the container after it is stopped.

I find myself using this flag every single time I start a container. As a matter of fact, I have never come across a use case where I don't want the --rm flag.

Per Docker best practices, containers should be ephemeral so keeping a container after it has been stopped seems like an anti-pattern.

Two questions:

  1. Is there a good situation for excluding the --rm flag?
  2. If excluding the -rm flag is so uncommon, why is --rm not the default behavior?

Question 2 Hyposthesis

I suspect the answer to question 2 is based on Docker conservative approach to deleting objects. Per the pruning docs:

Docker takes a conservative approach to cleaning up unused objects (often referred to as “garbage collection”), such as images, containers, volumes, and networks: these objects are generally not removed unless you explicitly ask Docker to do so.

Docker probably doesn't want to delete objects and surprise the user because that action can't be undone.

CodePudding user response:

I usually use either the --rm (delete when container exits) or -d (run in background) options; pretty much always one or the other, but not both.

Say you start a very typical service container and go home

docker run -d -p 8080:3000 --net some-network myimage

You come back in the morning and it's exited.

If you had started the container with --rm also, all trace of the container would be gone. You wouldn't see its exit status, or be able to review its docker logs. That can be a frustrating situation to recover from.

For "one-off" containers, --rm is probably right.

# run database migrations, in the foreground, printing status
# to stdout; nothing to preserve here
docker run --rm --net some-network myimage \
  ./manage.py migrate

I can't speak to why there's a --rm option rather than a --keep option, but it's been that way as long as I've been using Docker.

  • Related