Container Management - docker/docker-py

Container Management with python-on-whales

python-on-whales is a Python library that provides a 1-to-1 mapping between the Docker CLI and the Python library. It communicates with the Docker CLI instead of calling directly the Docker Engine HTTP API. This library is useful for managing the lifecycle of containers, including starting, stopping, restarting, deleting, and getting information about running containers.

Installation

To install python-on-whales, run the following command:

pip install python-on-whales

Basic Usage

Here’s an example of how to use python-on-whales to run a container:

from python_on_whales import docker

my_container = docker.run("ubuntu", ["sleep", "infinity"], detach=True)
print(my_container.state.started_at)
print(my_container.state.running)
my_container.kill()
my_container.remove()

In this example, we run an Ubuntu container in the background with the docker.run() function. We then print the container’s start time and running status. Finally, we kill and remove the container.

Getting Information about Running Containers

To get information about running containers, you can use the docker.containers() function. Here’s an example:

from python_on_whales import docker

containers = docker.containers()
for container in containers:
print(container.name, container.status)

In this example, we get a list of all running containers and print their names and statuses.

Building Images

To build an image with python-on-whales, you can use the docker.images.build() function. Here’s an example:

from python_on_whales import docker

my_image = docker.images.build(path=".", dockerfile="Dockerfile")
print(my_image.config.cmd)

In this example, we build an image from the current directory using the Dockerfile in that directory. We then print the image’s command.

Sources