I am trying to find if a Docker Container with a specific name exists, but I seem to be unsuccessful. I have found multiple answers from other posts, the most notable one being this one, but I cannot seem to reproduce their success. Their answer returns nothing when it is tried with the container in multiple states (sometimes stopped, sometimes running), but I can't seem to get an output. It is not supposed to do anything if the container is running for right now. The block of code that I've been using is:
if [ ! "$(docker ps -q -f name=mysql80)" ]; then
if [ "$(docker ps -aq -f status=exited -f name=mysql80)" ]; then
# cleanup
docker rm mysql80
fi
# run your container
docker run -d -p 3306:3306 -p 33060:33060 --volume "$MYSQLFOLDERLOCATION":/var/lib/mysql --name mysql80 frostedflakez/php-mysql-webserver:0.9-beta.3-mysql-latest-8.0
fi
I expect this block of code to find the container, and remove it if it is exited. I know this can sometimes be hazardous. I am running macOS 10.15.6 Catalina (latest update), with Docker Desktop 2.3.0.4 (46911)
.
% docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1300b4021189 frostedflakez/php-mysql-webserver:0.9-beta.3-mysql-latest-8.0 "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 0.0.0.0:3306->3306/tcp, 0.0.0.0:33060->33060/tcp mysql80
4e83c877642b frostedflakez/php-mysql-webserver:0.9-beta.3-php-latest-7.4 "docker-php-entrypoi…" 8 seconds ago Up 6 seconds 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp php74
^^^ This is my docker ps
output
Your script works for me. First run:
Second run:
and if I stop the container, and then run the script:
(I added a
echo "deleting mysql80"
just to help to know what was going on)If I stop and delete the container, and run the script, I get:
I'm running
Docker version 19.03.12, build 48a66213fe
on a Mac.