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.

90933 次浏览

我不确定我是否理解,docker-compose run —— user 是一个选项,而 docker-compose. yml 支持用户键(http://docs.docker.com/compose/yml/#working95dir-entrypoint-user-hostname-domainname-mem95limit-privileged-restart-stdin95open-tty-cpu95shares)。

我还没有找到任何选项来帮助您在 docker-compose.yml文件中定义这种行为,我认为解释是它会破坏一些 docker-compose ...命令应该如何工作。

更多关于 up/downstart/stop的资料:

docker-compose up builds, (re)creates, starts, and attaches to containers for a service.

由于您的 images已经构建,而且您的服务的 containers已经启动,因此您可以使用 docker-compose stopdocker-compose start来启动/停止您的服务。这不同于 docker-compose down:

停止容器并删除由 up创建的容器、网络、卷和图像。

你正在尝试做的事情的问题:

If you docker-compose up and one of your containers finishes its task and gets (auto)removed, then you can't docker-compose stop and docker-compose start again. The removed container will not be there to start it again.


你可能想看看:

我对此的解决方案是创建一个小 bash 脚本,它可以在事后自动删除容器。

如果您使用的是 macOS,则可以将此脚本放在 usr/local/bin中。假设它的名称为 dco,然后可以运行 chmod +x usr/local/bin/dco使其可执行。在 Windows 上,我不知道如何让它工作,但在 Linux 上,它应该是类似的。

#! /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

只要运行 docker-compose up && docker-compose rm -fsv

https://docs.docker.com/compose/reference/rm

Removes stopped service containers

--force , -f      Don't ask to confirm removal
--stop , -s       Stop the containers, if required, before removing
--volumes , -v    Remove any anonymous volumes attached to containers

这个问题发布已经有一段时间了,但是我认为在2022年分享一些对我的案子有用的东西会有所帮助:) 但是请记住,这个解决方案仍然不能像原始作者希望实现的那样删除旧的容器。

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. 只使用 --force-recreate并不能解决这个问题,因为匿名卷仍然被重用。