'Auto remove container with docker-compose.yml
docker-compose run has a flag --rm that auto removes the container after run. I am wondering if theres an equivalent config with docker-compose.yml for a specific service, as one of which services i got in yml is a one off build process which should just output the compile file and disappear itself.
Solution 1:[1]
Simply run docker-compose up && docker-compose rm -fsv ?
Solution 2:[2]
My solution to this was to create a little bash script that automatically removes containers afterwards.
If you're on macOS, you can put this script in usr/local/bin. Assuming it's named dco, you can then run chmod +x usr/local/bin/dco to make it executable. On Windows, I have no idea how to get this working, but on Linux it should be similar.
#! /bin/bash
# check for -d, --detached
DETACHED=false
for (( i=1; i <= "$#"; i++ )); do
ARG="${!i}"
case "$ARG" in
-d|--detach)
DETACHED=true
break
;;
esac
done
if [[ $1 == "run" ]] && [[ $DETACHED == false ]]; then
docker-compose run --rm "${@:2}"
elif [[ $1 == "up" ]] && [[ $DETACHED == false ]]; then
docker-compose up "${@:2}"; docker-compose down
else
docker-compose "${@:1}"
fi
Edit: Updated the script so that detached mode will work normally, added break to the loop suggested by artu-hnrq
Solution 3:[3]
It's been quite some time since this question was posted, but I thought it would be informative to share something that worked for my case, in 2022 :) But keep in mind that this solution still does not remove old containers, as the original author intended to achieve.
docker-compose up --force-recreate -V
In my case, I have a small Redis cluster where I want the data to be completely erased after I stop the servers.
Only using --force-recreate didn't do the trick, because the anonymous volume is still reused. That's where -V comes in.
Solution 4:[4]
I'm not sure I understand, docker-compose run --user is an option, and the docker-compose.yml supports the user key (http://docs.docker.com/compose/yml/#working95dir-entrypoint-user-hostname-domainname-mem95limit-privileged-restart-stdin95open-tty-cpu95shares).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Dharman |
| Solution 4 | Zehra |
