Skip to main content

Container

Struct Container 

Source
pub struct Container { /* private fields */ }
Expand description

A Docker container

Implementations§

Source§

impl Container

Source

pub fn new<T>(client: Arc<Docker>, image: T) -> Self
where T: Into<String>,

Create a new Container

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

// We can now start our container
container.start(true).await?;
Source

pub async fn from_id<T>(client: Arc<Docker>, id: T) -> Result<Self, Error>
where T: AsRef<str>,

Attempt to fetch an existing container by its ID

§Errors
  • Docker inspect fails
  • The container isn’t found
§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

// We can now start our container and grab its id
container.start(false).await?;

let id = container.id().unwrap();

let container2 = Container::from_id(connection.client(), id).await?;

assert_eq!(container.id(), container2.id());
Source

pub fn env( &mut self, env: impl IntoIterator<Item = impl Into<String>>, ) -> &mut Self

Set the environment variables for the container

NOTE: This will override any existing variables.

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

container.env(["FOO=BAR", "BAZ=QUX"]);

// We can now start our container, and the "FOO" and "BAZ" env vars will be set
container.start(true).await?;
Source

pub fn cmd( &mut self, cmd: impl IntoIterator<Item = impl Into<String>>, ) -> &mut Self

Set the command to run

The command is provided as a list of strings.

NOTE: This will override any existing command

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

container.cmd(["echo", "Hello!"]);

// We can now start our container, and the command "echo Hello!" will run
container.start(true).await?;
Source

pub fn binds( &mut self, binds: impl IntoIterator<Item = impl Into<String>>, ) -> &mut Self

Set a list of volume binds

These binds are in the standard host:dest[:options] format. For more information, see the Docker documentation.

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

// Mount './my-host-dir' at '/some/container/dir' and make it read-only
container.binds(["./my-host-dir:/some/container/dir:ro"]);

// We can now start our container
container.start(true).await?;
Source

pub fn extra_hosts( &mut self, hosts: impl IntoIterator<Item = impl Into<String>>, ) -> &mut Self

Add entries to the container’s /etc/hosts (equivalent to --add-host)

Each item should be "hostname:IP" (e.g. "host.docker.internal:host-gateway").

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

// Bind `host.docker.internal` (in the container) to the host gateway
container.extra_hosts(["host.docker.internal:host-gateway"]);

// We can now start our container
container.start(true).await?;
Source

pub fn id(&self) -> Option<&str>

Get the container ID if it has been created

This will only have a value if Container::create or Container::start has been called prior.

Source

pub async fn create(&mut self) -> Result<(), Error>

Attempt to create the container

This will take the following into account:

Be sure to set these before calling this!

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

container.env(["FOO=BAR", "BAZ=QUX"]);
container.cmd(["echo", "Hello!"]);
container.binds(["./host-data:/container-data"]);

// The container is created using the above settings
container.create().await?;

// Now it can be started
container.start(true).await?;
Source

pub async fn start(&mut self, wait_for_exit: bool) -> Result<(), Error>

Attempt to start the container

NOTE: If the container has not yet been created, this will attempt to call Container::create first.

wait_for_exit will wait for the container to exit before returning.

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

container.cmd(["echo", "Hello!"]);

// We can now start our container, and the command "echo Hello!" will run.
let wait_for_exit = true;
container.start(wait_for_exit).await?;

// Since we waited for the container to exit, we don't have to stop it.
// It can now just be removed.
container.remove(None).await?;
Source

pub async fn status(&self) -> Result<Option<ContainerStatus>, Error>

Checks if the container has not exited and is marked as healthy

NOTE: If the container has not yet been created, this will immediately return None.

§Errors
  • Failed to get the list of containers
  • The container status could not be parsed
§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;
use std::time::Duration;
use tokio::time;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

container.cmd(["echo", "Hello!"]);

let wait_for_exit = false;
container.start(wait_for_exit).await?;

loop {
    let status = container.status().await?.unwrap();
    if status.is_active() {
        time::sleep(Duration::from_secs(5)).await;
        continue;
    }

    println!("Container exited!");
    break;
}
Source

pub async fn stop(&mut self) -> Result<(), Error>

Stop a running container

NOTE: It is not an error to call this on a container that has not been started, it will simply do nothing.

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;

let mut container = Container::new(connection.client(), "rustlang/rust");

// Does nothing, the container isn't started
container.stop().await?;

// Stops the running container
container.start(false).await?;
container.stop().await?;
Source

pub async fn remove( self, options: Option<RemoveContainerOptions>, ) -> Result<(), Error>

Remove a container

NOTE: To remove a running container, a [RemoveContainerOptions] must be provided with the force flag set.

See also: bollard::container::RemoveContainerOptions

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;

let mut container = Container::new(connection.client(), "rustlang/rust");

// Start our container
container.start(false).await?;

let remove_container_options = bollard::container::RemoveContainerOptions {
    force: true,
    ..Default::default()
};

// Kills the container and removes it
container.remove(Some(remove_container_options)).await?;
Source

pub async fn wait(&self) -> Result<(), Error>

Wait for a container to exit

NOTE: It is not an error to call this on a container that has not been started, it will simply do nothing.

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;

let connection = DockerBuilder::new().await?;

let mut container = Container::new(connection.client(), "rustlang/rust");

// Start our container
container.start(false).await?;

// Once this returns, we know that the container has exited.
container.wait().await?;
Source

pub async fn logs( &self, logs_options: Option<LogsOptions<String>>, ) -> Option<impl Stream<Item = Result<LogOutput, Error>>>

Fetch the container log stream

NOTE: It is not an error to call this on a container that has not been started, it will simply do nothing and return None.

See also:

§Examples
use docktopus::DockerBuilder;
use docktopus::container::Container;
use futures::StreamExt;

let connection = DockerBuilder::new().await?;
let mut container = Container::new(connection.client(), "rustlang/rust");

// Start our container and wait for it to exit
container.start(true).await?;

// We want to collect logs from stderr
let logs_options = bollard::container::LogsOptions {
    stderr: true,
    follow: true,
    ..Default::default()
};

// Get our log stream
let mut logs = container
    .logs(Some(logs_options))
    .await
    .expect("logs should be present");

// Now we want to print anything from stderr
while let Some(Ok(out)) = logs.next().await {
    if let bollard::container::LogOutput::StdErr { message } = out {
        eprintln!("Uh oh! Something was written to stderr: {:?}", message);
    }
}

Trait Implementations§

Source§

impl Debug for Container

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> MaybeSendSync for T

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more