docker-compose: option to automaticaly remove container after run in docker-compose.yml
Solution 1:
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
Solution 2:
It's not part of the Dockerfile
or docker-compose.yml
spec, it is only a cli option for the run command, so the answer is no. You will need to rely on something external for enforcing.
If you got some build tool for your project it is usually best to wrap docker-compose tasks with that. For example our gradle projects provide docker related tasks that set some default options like --rm
for run tasks.