user11946462
user11946462

Reputation:

Docker SDK Python run container if it isn't aleardy running

My goal is to only run the container if it isn't already running.

What I tried is using client.containers.get(containername) and checking if it is None but that won't work because it returns an error message and not a bool.

if client.containers.get('containername') is not None:
   client.containeres.run("redis:latest",name="containerename", detach=True, ports={'6379/tcp': ('localhost', 6379)})

I get:

docker.error.notFound: 404 Client Error: Not Found("No such container: containername")

Is there any way I can manage to check if the redis container is already running and only run the container if it doesn't?

Upvotes: 0

Views: 722

Answers (1)

olned64
olned64

Reputation: 41

What about to use containers.list?

if len(client.containers.list(filters = {'name' : 'containername'})) == 0:
  ...

Upvotes: 1

Related Questions