Skip to content

container

Container

Container(image: Image, client: Optional[DockerClient] = None)

A class to manage a Docker container.

This class provides methods to create a container with specified runtime configurations, manage network connections, and control the container's lifecycle (start, stop, remove, logs, wait).

Attributes:

  • _image (Image) –

    The Docker image object to be used.

  • _client (DockerClient) –

    The Docker client instance.

  • _container (Optional[Container]) –

    The underlying Docker container object.

Initialize a Container instance.

Parameters:

  • image (Image) –

    The Image object that provides the Docker image details.

  • client (Optional[DockerClient], default: None ) –

    An optional Docker client instance. If not provided, docker.from_env() is used.

Examples:

>>> from ures.docker.image import Image
>>> img = Image("myapp")
>>> container = Container(img)
Source code in ures/docker/container.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def __init__(self, image: Image, client: Optional[docker.DockerClient] = None):
    """
    Initialize a Container instance.

    Args:
        image (Image): The Image object that provides the Docker image details.
        client (Optional[docker.DockerClient]): An optional Docker client instance. If not provided,
            docker.from_env() is used.

    Examples:
        >>> from ures.docker.image import Image
        >>> img = Image("myapp")
        >>> container = Container(img)
    """
    self._image: Image = image
    self._client: docker.DockerClient = client or docker.from_env()
    self._container: Optional[DockerContainer] = None

image_name property

image_name: str

Retrieve the full image name (including tag).

Returns:

  • str ( str ) –

    The full image name.

Examples:

>>> container.image_name
'myapp:latest'

is_created property

is_created: bool

Check whether the container has been created.

Returns:

  • bool ( bool ) –

    True if the container exists, False otherwise.

Examples:

>>> container.is_created
False

status property

status: str

Get the current status of the container.

Returns:

  • str ( str ) –

    The container status. If not found, returns "removed".

Examples:

>>> status = container.status
>>> status in ["created", "running", "exited", "removed"]
True

exit_code property

exit_code: int | None

Retrieve the exit code of the container's last run.

Returns:

  • int | None –

    The exit code if Docker still knows the container, otherwise None.

Examples:

>>> code = container.exit_code
>>> isinstance(code, int) or code is None
True

is_running property

is_running: bool

Check if the container is currently running.

Returns:

  • bool ( bool ) –

    True if running, False otherwise.

Examples:

>>> container.is_running
True

create

create(config: RuntimeConfig, tag: Optional[str] = None)

Create a Docker container using the provided runtime configuration.

Parameters:

  • config (RuntimeConfig) –

    The runtime configuration for the container.

  • tag (Optional[str], default: None ) –

    An optional image tag override. Defaults to None.

Examples:

>>> container.create(runtime_config)
>>> container.is_created
True
Source code in ures/docker/container.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def create(self, config: RuntimeConfig, tag: Optional[str] = None):
    """
    Create a Docker container using the provided runtime configuration.

    Args:
        config (RuntimeConfig): The runtime configuration for the container.
        tag (Optional[str]): An optional image tag override. Defaults to None.

    Examples:
        >>> container.create(runtime_config)
        >>> container.is_created
        True
    """
    if config.image_name != self.image_name or tag != self._image.tag:
        config.image_name = self._image.get_fullname(tag=tag)
        logger.warning(f"The image name is updated to {config.image_name}")
    run_params = self._construct_build_params(config)
    logger.debug(
        f"Create {self.image_name} with running Configuration: {json.dumps(run_params)}"
    )
    _container = self._client.containers.create(**run_params)
    self._connect_to_network(_container, config)
    self._container = _container

stop

stop()

Stop the running container.

Examples:

>>> container.stop()
Source code in ures/docker/container.py
283
284
285
286
287
288
289
290
291
292
@check_instance_variable("_container")
def stop(self):
    """
    Stop the running container.

    Examples:
        >>> container.stop()
    """
    logger.debug(f"Stopping container: {self.image_name}")
    self._container.stop()

remove

remove()

Remove the container.

Examples:

>>> container.remove()
Source code in ures/docker/container.py
294
295
296
297
298
299
300
301
302
303
304
@check_instance_variable("_container")
def remove(self):
    """
    Remove the container.

    Examples:
        >>> container.remove()
    """
    logger.debug(f"Removing container: {self.image_name}")
    self._container.remove()
    self._container = None

logs

logs() -> bytes

Retrieve logs from the container.

Returns:

  • bytes –

    Raw log output from the Docker SDK.

Examples:

>>> logs = container.logs()
>>> isinstance(logs, bytes)
True
Source code in ures/docker/container.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
@check_instance_variable("_container")
def logs(self) -> bytes:
    """
    Retrieve logs from the container.

    Returns:
        Raw log output from the Docker SDK.

    Examples:
        >>> logs = container.logs()
        >>> isinstance(logs, bytes)
        True
    """
    logger.debug(f"Retrieving logs from container: {self.image_name}")
    return self._container.logs()

wait

wait()

Wait for the container to finish execution.

Blocks until the Docker container stops. The Docker SDK result is not returned; inspect exit_code afterwards if you need the status.

Examples:

>>> container.wait()
Source code in ures/docker/container.py
322
323
324
325
326
327
328
329
330
331
332
333
334
@check_instance_variable("_container")
def wait(self):
    """
    Wait for the container to finish execution.

    Blocks until the Docker container stops. The Docker SDK result is not
    returned; inspect ``exit_code`` afterwards if you need the status.

    Examples:
        >>> container.wait()
    """
    logger.debug(f"Waiting for container to finish: {self.image_name}")
    self._container.wait()

run

run()

Start the container if it has been created and is not already running.

Raises:

  • RuntimeError –

    If the container has not been created or is already running.

Examples:

>>> container.run()
>>> container.is_running
True
Source code in ures/docker/container.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def run(self):
    """
    Start the container if it has been created and is not already running.

    Raises:
        RuntimeError: If the container has not been created or is already running.

    Examples:
        >>> container.run()
        >>> container.is_running
        True
    """
    if self.is_created is True and self.is_running is False:
        self._container.start()
        logger.debug(f"Container started: {self.image_name}")
    else:
        if self.is_created is False:
            raise RuntimeError(f"Container has not been created: {self.image_name}")
        if self.is_running is True:
            raise RuntimeError(f"Container already running: {self.image_name}")