How to run a docker container if not already running

I would definitely suggest looking into docker-compose and docker-compose up as answered above.

Since your question is about docker run, i would simplify the answer of VonC like this

docker start nginx || docker run --name nginx -d nginx

If the container already is running, docker start will return 0 thus no docker run is executed. If the container EXISTS but is not running, docker start will start it, otherwise it docker run creates and starts it in one go.

The "exists but stopped" part is missing in VonC's answer.


Use a filter to check if a container of a certain name exists:
(See docker ps Filterring)

#!/bin/bash

name='nginx'

[[ $(docker ps -f "name=$name" --format '{{.Names}}') == $name ]] ||
docker run --name "$name" -d nginx

The docker run will only be executed if the first part is false.

To be on the safe side (docker ps might return several names), you might alternatively do (if you think the word "nginx" can't be part of any container name):

if ! docker ps --format '{{.Names}}' | grep -w nginx &> /dev/null; then
    docker run --name nginx -d nginx
fi

Or:

if ! docker ps --format '{{.Names}}' | egrep '^nginx$' &> /dev/null; then
    docker run --name nginx -d nginx
fi

Tags:

Docker

Bash