docker container
ContainerCLI
attach
attach(container, detach_keys=None, stdin=True, sig_proxy=True)
Attach local standard input, output, and error streams to a running container
Alias: docker.attach(...)
PARAMETER | DESCRIPTION |
---|---|
container |
The running container to attach to
TYPE:
|
detach_keys |
Override the key sequence for detaching a container
TYPE:
|
stdin |
Attach STDIN
TYPE:
|
sig_proxy |
Proxy all received signals to the process (default true)
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
commit
commit(container, tag=None, author=None, message=None, pause=True)
Create a new image from a container's changes
PARAMETER | DESCRIPTION |
---|---|
container |
The container to create the image from
TYPE:
|
tag |
tag to apply on the image produced
TYPE:
|
author |
Author (e.g., "John Hannibal Smith hannibal@a-team.com")
TYPE:
|
message |
Commit message
TYPE:
|
pause |
Pause container during commit
TYPE:
|
copy
copy(source, destination)
Copy files/folders between a container and the local filesystem
Alias: docker.copy(...)
from python_on_whales import docker
docker.run("ubuntu", ["sleep", "infinity"], name="dodo", remove=True, detach=True)
docker.copy("/tmp/my_local_file.txt", ("dodo", "/path/in/container.txt"))
docker.copy(("dodo", "/path/in/container.txt"), "/tmp/my_local_file2.txt")
Doesn't yet support sending or receiving iterators of Python bytes.
PARAMETER | DESCRIPTION |
---|---|
source |
Local path or tuple. When using a tuple, the first element
of the tuple is the container, the second element is the path in
the container. ex:
TYPE:
|
destination |
Local path or tuple. When using a tuple, the first element
of the tuple is the container, the second element is the path in
the container. ex:
TYPE:
|
create
create(image, command=(), *, add_hosts=(), blkio_weight=None, blkio_weight_device=(), cap_add=(), cap_drop=(), cgroup_parent=None, cgroupns=None, cidfile=None, cpu_period=None, cpu_quota=None, cpu_rt_period=None, cpu_rt_runtime=None, cpu_shares=None, cpus=None, cpuset_cpus=None, cpuset_mems=None, detach=False, devices=(), device_cgroup_rules=(), device_read_bps=(), device_read_iops=(), device_write_bps=(), device_write_iops=(), content_trust=False, dns=(), dns_options=(), dns_search=(), domainname=None, entrypoint=None, envs={}, env_files=[], env_host=False, expose=(), gpus=None, groups_add=(), healthcheck=True, health_cmd=None, health_interval=None, health_retries=None, health_start_period=None, health_timeout=None, hostname=None, init=False, interactive=False, ip=None, ip6=None, ipc=None, isolation=None, kernel_memory=None, labels={}, label_files=(), link=(), link_local_ip=(), log_driver=None, log_options=(), mac_address=None, memory=None, memory_reservation=None, memory_swap=None, memory_swappiness=None, mounts=(), name=None, networks=(), network_aliases=(), oom_kill=True, oom_score_adj=None, pid=None, pids_limit=None, platform=None, pod=None, privileged=False, publish=(), publish_all=False, pull='missing', read_only=False, restart=None, remove=False, runtime=None, security_options=(), shm_size=None, sig_proxy=True, stop_signal=None, stop_timeout=None, storage_options=(), sysctl={}, systemd=None, tmpfs=(), tty=False, tz=None, ulimit=(), user=None, userns=None, uts=None, volumes=(), volume_driver=None, volumes_from=(), workdir=None)
Creates a container, but does not start it.
Alias: docker.create(...)
Start it then with the .start()
method.
It might be useful if you want to delay the start of a container,
to do some preparations beforehand. For example, it's common to do this
workflow: docker create
-> docker cp
-> docker start
to put files
in the container before starting.
There is no detach
argument since it's a runtime option.
The arguments are the same as docker.run
.
diff
diff(container)
List all the files modified, added or deleted since the container started.
Alias: docker.diff(...)
PARAMETER | DESCRIPTION |
---|---|
container |
The container to inspect
TYPE:
|
Returns
`Dict[str, str]` Something like
`{"/some_path": "A", "/some_file": "M", "/tmp": "D"}` for example.
execute
execute(container, command, detach=False, envs={}, env_files=(), interactive=False, privileged=False, tty=False, user=None, workdir=None, stream=False, detach_keys=None, preserve_fds=None)
Execute a command inside a container
Alias: docker.execute(...)
PARAMETER | DESCRIPTION |
---|---|
container |
The container to execute the command in.
TYPE:
|
command |
The command to execute.
TYPE:
|
detach |
if
TYPE:
|
envs |
Set environment variables
TYPE:
|
env_files |
Read one or more files of environment variables
TYPE:
|
interactive |
Leave stdin open during the duration of the process
to allow communication with the parent process.
Currently only works with
TYPE:
|
preserve_fds |
The number of additional file descriptors to pass through to the container. Only supported by podman.
TYPE:
|
privileged |
Give extended privileges to the container.
TYPE:
|
tty |
Allocate a pseudo-TTY. Allow the process to access your terminal to write on it.
TYPE:
|
user |
Username or UID, format:
TYPE:
|
workdir |
Working directory inside the container
TYPE:
|
stream |
Similar to
TYPE:
|
detach_keys |
Override the key sequence for detaching a container.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Union[None, str, Iterable[Tuple[str, bytes]]]
|
Optional[str] |
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
exists
exists(x)
Returns True
if the container exists. False
otherwise.
It's just calling docker.container.inspect(...)
and verifies that it doesn't throw
a python_on_whales.exceptions.NoSuchContainer
.
Returns
A `bool`
export
export(container, output)
Export a container's filesystem as a tar archive
Alias: docker.export(...)
PARAMETER | DESCRIPTION |
---|---|
container |
The container to export.
TYPE:
|
output |
The path of the output tar archive. Returning a generator of bytes is not yet implemented.
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
init
init(containers)
Initialize one or more containers.
Note that this is only supported by podman.
Alias: docker.init(...)
PARAMETER | DESCRIPTION |
---|---|
containers |
One or more containers to kill
TYPE:
|
output |
The path of the output tar archive. Returning a generator of bytes is not yet implemented.
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if any of the
containers do not exist.
inspect
inspect(x)
Returns a container object from a name or ID.
PARAMETER | DESCRIPTION |
---|---|
x |
A container name or ID, or a list of container names and/or IDs
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Union[Container, List[Container]]
|
A |
Union[Container, List[Container]]
|
if a list of IDs was passed as input. |
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
kill
kill(containers, signal=None)
Kill one or more containers.
Alias: docker.kill(...)
PARAMETER | DESCRIPTION |
---|---|
containers |
One or more containers to kill
TYPE:
|
signal |
The signal to send the container
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if any of the
containers do not exist.
list
list(all=False, filters={})
List the containers on the host.
Alias: docker.ps(...)
PARAMETER | DESCRIPTION |
---|---|
all |
If
TYPE:
|
Returns
A `List[python_on_whales.Container]`
logs
logs(container, *, details=False, since=None, tail=None, timestamps=False, until=None, follow=False, stream=False)
Returns the logs of a container as a string or an iterator.
Alias: docker.logs(...)
PARAMETER | DESCRIPTION |
---|---|
container |
The container to get the logs of
TYPE:
|
details |
Show extra details provided to logs
TYPE:
|
since |
Use a datetime or timedelta to specify the lower date limit for the logs.
TYPE:
|
tail |
Number of lines to show from the end of the logs (default all)
TYPE:
|
timestamps |
Put timestamps next to lines.
TYPE:
|
until |
Use a datetime or a timedelta to specify the upper date limit for the logs.
TYPE:
|
follow |
If
TYPE:
|
stream |
Similar to the
TYPE:
|
Returns
`str` if `stream=False` (the default), `Iterable[Tuple[str, bytes]]`
if `stream=True`.
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exist.
If you are a bit confused about follow
and stream
, here are some use cases.
- If you want to have the logs up to this point as a
str
, don't use those args. - If you want to stream the output in real time, use
follow=True, stream=True
- If you want the logs up to this point, but you don't want to fit all the logs
in memory because they are too big, use
stream=True
.
pause
pause(containers)
Pauses one or more containers
Alias: docker.pause(...)
PARAMETER | DESCRIPTION |
---|---|
containers |
One or more containers to pause
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
prune
prune(filters={}, stream_logs=False)
Remove containers that are not running.
PARAMETER | DESCRIPTION |
---|---|
filters |
Filters as strings or list of strings
TYPE:
|
stream_logs |
If
TYPE:
|
remove
remove(containers, *, force=False, volumes=False)
Removes a container
Alias: docker.remove(...)
PARAMETER | DESCRIPTION |
---|---|
containers |
One or more containers.
TYPE:
|
force |
Force the removal of a running container (uses SIGKILL)
TYPE:
|
volumes |
Remove anonymous volumes associated with the container
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
rename
rename(container, new_name)
Changes the name of a container.
Alias: docker.rename(...)
PARAMETER | DESCRIPTION |
---|---|
container |
The container to rename
TYPE:
|
new_name |
The new name of the container.
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exist.
restart
restart(containers, time=None)
Restarts one or more container.
Alias: docker.restart(...)
PARAMETER | DESCRIPTION |
---|---|
containers |
One or more containers to restart
TYPE:
|
time |
Amount of to wait for stop before killing the container (default 10s).
If
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
run
run(image, command=(), *, add_hosts=(), blkio_weight=None, blkio_weight_device=(), cap_add=(), cap_drop=(), cgroup_parent=None, cgroupns=None, cidfile=None, cpu_period=None, cpu_quota=None, cpu_rt_period=None, cpu_rt_runtime=None, cpu_shares=None, cpus=None, cpuset_cpus=None, cpuset_mems=None, detach=False, devices=(), device_cgroup_rules=(), device_read_bps=(), device_read_iops=(), device_write_bps=(), device_write_iops=(), content_trust=False, dns=(), dns_options=(), dns_search=(), domainname=None, entrypoint=None, envs={}, env_files=(), env_host=False, expose=(), gpus=None, groups_add=(), healthcheck=True, health_cmd=None, health_interval=None, health_retries=None, health_start_period=None, health_timeout=None, hostname=None, init=False, interactive=False, ip=None, ip6=None, ipc=None, isolation=None, kernel_memory=None, labels={}, label_files=(), link=(), link_local_ip=(), log_driver=None, log_options=(), mac_address=None, memory=None, memory_reservation=None, memory_swap=None, memory_swappiness=None, mounts=(), name=None, networks=(), network_aliases=(), oom_kill=True, oom_score_adj=None, pid=None, pids_limit=None, platform=None, pod=None, preserve_fds=None, privileged=False, publish=(), publish_all=False, pull='missing', read_only=False, restart=None, remove=False, runtime=None, security_options=(), shm_size=None, sig_proxy=True, stop_signal=None, stop_timeout=None, storage_options=(), stream=False, sysctl={}, systemd=None, tmpfs=(), tty=False, tz=None, ulimit=(), user=None, userns=None, uts=None, volumes=(), volume_driver=None, volumes_from=(), workdir=None)
Runs a container
You can use docker.run
or docker.container.run
to call this function.
For a deeper dive into the arguments and what they do, visit https://docs.docker.com/engine/reference/run/
If you want to know exactly how to call docker.run()
depending on your
use case (detach, stream...), take a look at
the docker.run()
guide.
>>> from python_on_whales import docker
>>> returned_string = docker.run("hello-world")
>>> print(returned_string)
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
>>> from python_on_whales import docker
>>> result_string = docker.run("ubuntu", ["ls", "/host"], volumes=[("/", "/host", "ro")])
>>> print(result_string)
bin
boot
dev
etc
home
init
lib
lib64
lost+found
media
mnt
opt
proc
projects
root
run
sbin
snap
srv
sys
tmp
usr
var
PARAMETER | DESCRIPTION |
---|---|
image |
The image to use for the container.
TYPE:
|
command |
Sequence of arguments to provide to the container.
TYPE:
|
add_hosts |
hosts to add in the format of a tuple. For example,
TYPE:
|
blkio_weight |
Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
TYPE:
|
cgroupns |
Cgroup namespace mode to use, one of 'host' or 'private'.
TYPE:
|
cpu_period |
Limit CPU CFS (Completely Fair Scheduler) period
TYPE:
|
cpu_quota |
Limit CPU CFS (Completely Fair Scheduler) quota
TYPE:
|
cpu_rt_period |
Limit CPU real-time period in microseconds
TYPE:
|
cpu_rt_runtime |
Limit CPU real-time runtime in microseconds
TYPE:
|
cpu_shares |
CPU shares (relative weight)
TYPE:
|
cpus |
The maximal amount of cpu the container can use.
TYPE:
|
cpuset_cpus |
CPUs in which to allow execution. Must be given as a list.
TYPE:
|
cpuset_mems |
MEMs in which to allow execution. Must be given as a list.
TYPE:
|
detach |
If
TYPE:
|
dns_search |
Set custom DNS search domains
TYPE:
|
domainname |
Container NIS domain name
TYPE:
|
entrypoint |
Overwrite the default ENTRYPOINT of the image
TYPE:
|
envs |
Environment variables as a
TYPE:
|
env_files |
One or a list of env files.
TYPE:
|
env_host |
Use host environment inside the container. Only supported with podman.
TYPE:
|
gpus |
For this to work, you need the
Nvidia container runtime
The value needed is a
TYPE:
|
hostname |
Container host name
TYPE:
|
interactive |
Leave stdin open during the duration of the process
to allow communication with the parent process.
Currently only works with
TYPE:
|
ip |
IPv4 address (e.g., 172.30.100.104)
TYPE:
|
ip6 |
IPv6 address (e.g., 2001:db8::33)
TYPE:
|
ipc |
IPC mode to use
TYPE:
|
isolation |
Container isolation technology
TYPE:
|
kernel_memory |
Kernel memory limit.
TYPE:
|
labels |
Set meta data on a container. The labels can be used later when filtering
containers with
TYPE:
|
log_driver |
Logging driver for the container
TYPE:
|
mac_address |
Container MAC address (e.g.,
TYPE:
|
memory |
Memory limit, valid values are
TYPE:
|
memory_reservation |
Memory soft limit
TYPE:
|
memory_swap |
Swap limit equal to memory plus swap: '-1' to enable unlimited swap.
TYPE:
|
memory_swappiness |
Tune container memory swappiness (0 to 100) (default -1)
TYPE:
|
name |
The container name. If not provided, one is automatically genrated for you.
TYPE:
|
healthcheck |
Set to
TYPE:
|
oom_kill |
Set to
TYPE:
|
pid |
PID namespace to use
TYPE:
|
pids_limit |
Tune container pids limit (set
TYPE:
|
platform |
Set platform if server is multi-platform capable.
TYPE:
|
pod |
Create the container in an existing pod (only supported with podman).
TYPE:
|
preserve_fds |
The number of additional file descriptors to pass through to the container. Only supported by podman.
TYPE:
|
privileged |
Give extended privileges to this container.
TYPE:
|
publish |
Ports to publish, same as the
TYPE:
|
publish_all |
Publish all exposed ports to random ports.
TYPE:
|
pull |
Pull image before running ("always"|"missing"|"never") (default "missing").
TYPE:
|
read_only |
Mount the container's root filesystem as read only.
TYPE:
|
restart |
Restart policy to apply when a container exits (default "no")
TYPE:
|
remove |
Automatically remove the container when it exits.
TYPE:
|
runtime |
Runtime to use for this container.
TYPE:
|
security_options |
Security options
TYPE:
|
shm_size |
Size of /dev/shm.
TYPE:
|
stop_timeout |
Signal to stop a container (default "SIGTERM")
TYPE:
|
storage_options |
Storage driver options for the container
TYPE:
|
systemd |
Whether to run in systemd mode. Only known to apply to Podman, see https://docs.podman.io/en/latest/markdown/podman-run.1.html#systemd-true-false-always
TYPE:
|
tty |
Allocate a pseudo-TTY. Allow the process to access your terminal to write on it.
TYPE:
|
tz |
Set timezone in container, or
TYPE:
|
user |
Username or UID (format:
TYPE:
|
userns |
User namespace to use
TYPE:
|
uts |
UTS namespace to use
TYPE:
|
volumes |
Bind mount a volume. Some examples:
TYPE:
|
volume_driver |
Optional volume driver for the container
TYPE:
|
workdir |
The directory in the container where the process will be executed.
TYPE:
|
Returns
The container output as a string if detach is `False` (the default),
and a `python_on_whales.Container` if detach is `True`.
start
start(containers, attach=False, interactive=False, stream=False, detach_keys=None)
Starts one or more created/stopped containers.
Aliases: docker.start
, docker.container.start
,
python_on_whales.Container.start
.
PARAMETER | DESCRIPTION |
---|---|
containers |
One or a list of containers.
TYPE:
|
attach |
Attach stdout/stderr and forward signals.
TYPE:
|
interactive |
Attach stdin (ensure it is open).
TYPE:
|
stream |
Stream output as a generator.
TYPE:
|
detach_keys |
Override the key sequence for detaching a container.
TYPE:
|
stats
stats(containers=None, all=False)
Get containers resource usage statistics
Alias: docker.stats(...)
Usage:
from python_on_whales import docker
docker.run("redis", detach=True)
print(docker.stats())
# [<<class 'python_on_whales.components.container.ContainerStats'> object,
# attributes are block_read=0, block_write=0, cpu_percentage=0.08,
# container=e90ae41a5b17,
# container_id=e90ae41a5b17df998584141692f1e361c485e8d00c37ee21fdc360d3523dd1c1,
# memory_percentage=0.18, memory_used=11198791, memory_limit=6233071288,
# container_name=crazy_northcutt, net_upload=696, net_download=0>]
The data unit is the byte.
PARAMETER | DESCRIPTION |
---|---|
all |
Get the stats of all containers, not just running ones.
TYPE:
|
containers |
One or a list of containers.
TYPE:
|
Returns
A `List[python_on_whales.ContainerStats]`.
stop
stop(containers, time=None)
Stops one or more running containers
Alias: docker.stop(...)
Aliases: docker.stop
, docker.container.stop
,
python_on_whales.Container.stop
.
PARAMETER | DESCRIPTION |
---|---|
containers |
One or a list of containers.
TYPE:
|
time |
Seconds to wait for stop before killing a container (default 10)
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if any of the
containers do not exist.
top
top()
Get the running processes of a container
Alias: docker.top(...)
Not yet implemented
unpause
unpause(x)
Unpause all processes within one or more containers
Alias: docker.unpause(...)
PARAMETER | DESCRIPTION |
---|---|
x |
One or more containers (name, id or
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if any of the
containers do not exist.
update
update(x, /, *, blkio_weight=None, cpu_period=None, cpu_quota=None, cpu_rt_period=None, cpu_rt_runtime=None, cpu_shares=None, cpus=None, cpuset_cpus=None, cpuset_mems=None, kernel_memory=None, memory=None, memory_reservation=None, memory_swap=None, pids_limit=None, restart=None)
Update configuration of one or more containers
Alias: docker.update(...)
PARAMETER | DESCRIPTION |
---|---|
x |
One or a list of containers to update.
TYPE:
|
blkio_weight |
Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
TYPE:
|
cpu_period |
Limit CPU CFS (Completely Fair Scheduler) period
TYPE:
|
cpu_quota |
Limit CPU CFS (Completely Fair Scheduler) quota
TYPE:
|
cpu_rt_period |
Limit CPU real-time period in microseconds
TYPE:
|
cpu_rt_runtime |
Limit CPU real-time runtime in microseconds
TYPE:
|
cpu_shares |
CPU shares (relative weight)
TYPE:
|
cpus |
The maximal amount of cpu the container can use.
TYPE:
|
cpuset_cpus |
CPUs in which to allow execution. Must be given as a list.
TYPE:
|
cpuset_mems |
MEMs in which to allow execution. Must be given as a list.
TYPE:
|
memory |
Memory limit, valid values are
TYPE:
|
memory_reservation |
Memory soft limit
TYPE:
|
memory_swap |
Swap limit equal to memory plus swap: '-1' to enable unlimited swap.
TYPE:
|
pids_limit |
Tune container pids limit (set
TYPE:
|
restart |
Restart policy to apply when a container exits (default "no")
TYPE:
|
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.
wait
wait(x)
Block until one or more containers stop, then returns their exit codes
Alias: docker.wait(...)
PARAMETER | DESCRIPTION |
---|---|
x |
One or a list of containers to wait for.
TYPE:
|
Returns
An `int` if a single container was passed as argument or a list of ints
if multiple containers were passed as arguments.
Some Examples:
cont = docker.run("ubuntu", ["bash", "-c", "sleep 2 && exit 8"], detach=True)
exit_code = docker.wait(cont)
print(exit_code)
# 8
docker.container.remove(cont)
cont_1 = docker.run("ubuntu", ["bash", "-c", "sleep 4 && exit 8"], detach=True)
cont_2 = docker.run("ubuntu", ["bash", "-c", "sleep 2 && exit 10"], detach=True)
exit_codes = docker.wait([cont_1, cont_2])
print(exit_codes)
# [8, 10]
docker.container.remove([cont_1, cont_2])
Raises
`python_on_whales.exceptions.NoSuchContainer` if the container does not exists.