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