What is the '--rm' flag doing?

Containers are merely an instance of the image you use to run them. The state of mind when creating a containerized app is not by taking a fresh, clean ubuntu container for instance, and downloading the apps and configurations you wish to have in it, and then let it run.

You should treat the container as an instance of your application, but your application is embedded into an image. The proper usage would be creating a custom image, where you embed all your files, configurations, environment variables etc, into the image. Read more about Dockerfile and how it is done here

Once you did that, you have an image that contains everything, and in order to use your application, you just run the image with proper port settings or other dynamic variables, using docker run <your-image>

Running containers with --rm flag is good for those containers that you use for very short while just to accomplish something, e.g., compile your application inside a container, or just testing something that it works, and then you are know its a short lived container and you tell your Docker daemon that once its done running, erase everything related to it and save the disk space.


The flag --rm is used when you need the container to be deleted after the task for it is complete.

This is suitable for small testing or POC purposes and saves the headache for house keeping.


From https://docs.docker.com/engine/reference/run/#clean-up---rm

By default a container’s file system persists even after the container exits. This makes debugging a lot easier (since you can inspect the final state) and you retain all your data by default. But if you are running short-term foreground processes, these container file systems can really pile up. If instead you’d like Docker to automatically clean up the container and remove the file system when the container exits, you can add the --rm flag

In short, it's useful to keep the host clean from stopped and unused containers.


I use --rm when connecting to running containers to perform some actions such as database backup or file copy. Here is an example:

docker run -v $(pwd):/mnt --link app_postgres_1:pg --rm postgres:9.5 pg_dump -U postgres -h pg -f /mnt/docker_pg.dump1 app_db

The above will connect a running container named 'app_postgres_1' and create a backup. Once the backup command completes, the container is fully deleted.