How to list containers in Docker?

Asked

Viewed 419 times

3

I recently started testing on Docker, created a virtual machine and installed Debian 9 without a graphical interface. I know the command:

docker ps

Shows the running containers, there are other commands where I can search if a particular container has been created ?

For I will need to execute one Shell Script to check whether the container exists and is running.

Example:

$ sudo docker ps | grep 'recipiente-nome'

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 Don’t truncate output

--quiet , -q Only display Numeric Ids

--size-s Display total file

  • 2

    Very well, you could edit your answer and explain the parameter -a? For future reference.

  • You’re done, my friend, a hug

  • The condition is not working ! It is returning not found

  • @wmsouza edited the answer and put more alternatives, if you can test abs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.