Search code examples
dockershdocker-cli

See if a Docker Container Exists With a Specific Name


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


Solution

  • Your script works for me. First run:

    > t
    Unable to find image 'frostedflakez/php-mysql-webserver:0.9-beta.3-mysql-latest-8.0' locally
    0.9-beta.3-mysql-latest-8.0: Pulling from frostedflakez/php-mysql-webserver
    ...
    5e500ef7181b: Pull complete
    af7528e958b6: Pull complete
    Digest: sha256:ef35b9e2b11b0b42a40205eba89a2b8320ace58a3c073b43e1770a52a044484b
    Status: Downloaded newer image for frostedflakez/php-mysql-webserver:0.9-beta.3-mysql-latest-8.0
    8b01dd743c554a8fb79d73bccf683097e531e8eeea3af1062e0414b35401a000
    >
    

    Second run:

    > t
    >
    

    and if I stop the container, and then run the script:

    > t
    deleting mysql80
    mysql80
    35ca48875efdc60032b00325dd0563da64a834df0074580051c25e0601573180
    >
    

    (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:

    > t
    971309690a97d0b2ffb730feb9f19ab03db10df730d19c91c3482a952a9ebb18
    >
    

    I'm running Docker version 19.03.12, build 48a66213fe on a Mac.