Docker-compose: option to automaticaly remove container after run in docker-compose.yml

containersdocker

The docker-compose run reference states that it has the --rm option to

Remove container after run.

I want to make this a default run behavior for some of services I specify in docker-compose.yml.

So, the questions are:

  1. Can it somehow be specified in docker-compose.yml?
  2. If it can, how can I do that?

(INB4 "Use bash aliases, Luke!": Of course I can enforce this outside of docker-compose.yml by setting some bash alias like alias docker-compose-run='docker-compose run --rm' but I'm interested in how can I enforce that exactly through docker-compose.yml, not in some extrnal way.)

Best Answer

TLDR: It's still not possible 2018-11; use docker-compose down or docker-compose run --rm

I want to give an updated answer to this question because it's almost 3 years later. This will save others some searching.

I had the same question and here are the workarounds I found (including the one from the question itself):

docker-compose down

which does the following:

Stops containers and removes containers, networks, volumes, and images created by up.

By default, the only things removed are:

- Containers for services defined in the Compose file
- Networks defined in the networks section of the Compose file
- The default network, if one is used

Networks and volumes defined as external are never removed.

Although you cannot declare it in docker-compose.yml it will safe you some hassle; especially with volumes and networks.

docker-compose run --rm

--rm - Remove container after run. Ignored in detached mode.

Runs a one-time command against a service. For example, the following command starts the web service and runs bash as its command.

docker-compose run web bash

[...] the command passed by run overrides the command defined in the service configuration.

[...] the command does not create any of the ports specified in the service configuration. This prevents port collisions with already-open ports. If you do want the service’s ports to be created and mapped to the host, specify the --service-ports flag

docker-compose rm -f

-f, --force Don't ask to confirm removal