I need to run a docker container only if its not already running. Given this command. How would I run it only if it does not exists.
docker run --name nginx -d nginx
I am open to any script or language.
I need to run a docker container only if its not already running. Given this command. How would I run it only if it does not exists.
docker run --name nginx -d nginx
I am open to any script or language.
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 thisIf the container already is running,
docker start
will return0
thus nodocker run
is executed. If the container EXISTS but is not running,docker start
will start it, otherwise itdocker run
creates it.The "exists but stopped" part is missing in VonC's answer.
Well if you are open to any language I recommend using docker-compose for this task. After installing it, create a file called docker-compose.yml with this content:
Then use:
It will always check if the container is already running. If the container doesn't exists it will create it and run. If the container is stopped it just run it.
The best thing is if you alter the docker-compose.yml or pull a new version of the image it will automatically recreate the container preserving all volumes even the unnamed ones.
Regards
Use a filter to check if a container of a certain name exists:
(See docker ps Filterring)
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):Or: