How to list containers in Docker?

3

Recently I started doing tests in Docker, I created a virtual machine and installed Debian 9 without graphical interface. I know the command:

docker ps

Show running containers, are there other commands where I can search if a particular container was created?

I will need to run a Shell Script to check if the container exists and if it is running.

Example:

$ sudo docker ps | grep 'recipiente-nome'
    
asked by anonymous 22.01.2018 / 07:51

1 answer

4

You can do it this way:

CONTAINER_NAME='mycontainername'

CID=$(docker ps -q -f status=running -f name=^/${CONTAINER_NAME}$)
if [ ! "${CID}" ]; then
  echo "Container doesn't exist"
fi
unset CID

or

if [ ! "$(docker ps -q -f name=<name>)" ]; then
    if [ "$(docker ps -aq -f status=exited -f name=<name>)" ]; then
        # cleanup
        docker rm <name>
    fi
    # run your container
    docker run -d --name <name> my-docker-image
fi

For reference:

  

docker ps [OPTIONS]

     

Options

     

- all, -a Show all containers (default shows just running)

     

- filter, -f Filter output based on conditions provided

     

- format Pretty-print containers using a Go template

     

- last, -n -1 Show n last created containers (includes all states)

     

- latest, -l Show the latest created container (includes all states)

     

- no-trunc Do not truncate output

     

- quiet, -q Only display numeric IDs

     

- size, -s Display total file sizes

    
22.01.2018 / 09:06