Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping container alive with Docker Python SDK

Tags:

python

docker

I am using the Docker Sdk for Python to run my container.

I am trying to start a docker container, and then run a command using the api exec_run (I need the exit code). The exec_run needs to be executed on a started container.

This is my code:

import docker

client = docker.from_env()
container = client.containers.run('e7d8452ce5f5', command="echo starting", detach=True)
container.exec_run("echo execute command")

This raises an exception:

docker.errors.APIError: 409 Client Error: Conflict ("Container b65acd40f589819f490564dcb4e25f3055d85712cb7b2834ede5f2c4d57f2da6 is not running")

I tried running with no command when invoking client.containers.run, same exception..

Seems the container exists when the command is finished, even though in their documentation it is stated that the command run with detach=True is same as the cli docker run -d (when using docker run -d the container stays alive)

Any ideas on how to keep the container alive in order to call exec_run on it?

like image 352
dana racah Avatar asked Apr 05 '26 17:04

dana racah


1 Answers

When you use containers.run() method to start a ontainer,you should use tty parameter and set tty=True and then it will keep the container alive.

import docker
client = docker.from_env()
container = client.containers.run('xxxx', command="/bin/bash", tty=True,detach=True)
like image 180
lwzhuo Avatar answered Apr 08 '26 07:04

lwzhuo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!