This is my solution to check for a running container, stop it, then remove it.
CNAME=$CONTAINER_NAME-$CODE_VERSION
if [ "$(docker ps -qa -f name=$CNAME)" ]; then
echo ":: Found container - $CNAME"
if [ "$(docker ps -q -f name=$CNAME)" ]; then
echo ":: Stopping running container - $CNAME"
docker stop $CNAME;
fi
echo ":: Removing stopped container - $CNAME"
docker rm $CNAME;
fi
I've had to search this too many times because even the 100+ answer above doesn't actually work. I think the reason is a misunderstanding on docker ps. docker ps
lists RUNNING containers. docker ps -q
does the same but the output is striped to include only the container_id. docker ps -a
lists ALL containers (running or not). docker ps -qa
then is a simple list of all containers while docker ps -q
is a simple list of running containers. docker ps -q -f name=ContainerName
is then a simple list of running containers with the name ContainerName. docker ps -qa -f
would include exited containers as well so the logic must be to check -a (there, running or not), then without -a to see if it's not only there, but running (and needs to be stopped first).