Skip to main content

Docker

Struct Docker 

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

§Docker

The main interface for calling the Docker API. Construct a new Docker instance using one of the connect methods:

Implementations§

Source§

impl Docker

Source

pub async fn list_configs( &self, options: Option<ListConfigsOptions>, ) -> Result<Vec<Config>, Error>


§List Configs

Returns a list of configs.

§Arguments
§Returns
  • Vector of Config, wrapped in a Future.
§Examples
use bollard::query_parameters::ListConfigsOptionsBuilder;

use std::collections::HashMap;
use std::default::Default;

let mut filters = HashMap::new();
filters.insert("label", vec!["config-label=label-value"]);

let filters: HashMap<String, Vec<String>> = filters.into_iter().map(|(k, v)| (k.to_string(), v.into_iter().map(String::from).collect())).collect();
let options = ListConfigsOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_configs(Some(options));
Source

pub async fn create_config( &self, config_spec: ConfigSpec, ) -> Result<IdResponse, Error>


§Create Config

Create a new config on the docker swarm.

§Arguments
§Returns
§Examples
use bollard::config::ConfigSpec;

use base64;

let config_spec = ConfigSpec {
    name: Some(String::from("config-name")),
    data: Some(base64::engine::general_purpose::STANDARD.encode("config-data")),
    ..Default::default()
};

docker.create_config(config_spec);
Source

pub async fn inspect_config(&self, config_id: &str) -> Result<Config, Error>


§Inspect Config

Inspect a config.

§Arguments
  • Config id or name as a string slice.
§Returns
  • Config, wrapped in a Future.
§Examples

docker.inspect_config("config-id");
docker.inspect_config("config-name");
Source

pub async fn delete_config(&self, config_id: &str) -> Result<(), Error>


§Delete Config

Delete a config.

§Arguments
  • Config id or name as a string slice.
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.delete_config("config-id");
docker.delete_config("config-name");
Source

pub async fn update_config( &self, config_id: &str, config_spec: ConfigSpec, options: UpdateConfigOptions, ) -> Result<(), Error>


§Update Config

Update an existing config.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples

use std::collections::HashMap;
use bollard::query_parameters::UpdateConfigOptionsBuilder;

let result = async move {
    let existing = docker.inspect_config("my-config").await?;
    let version = existing.version.unwrap().index.unwrap();
    let mut spec = existing.spec.unwrap().clone();

    let mut labels = HashMap::new();
    labels.insert(String::from("config-label"), String::from("label-value"));
    spec.labels = Some(labels.clone());

    let options = UpdateConfigOptionsBuilder::default()
        .version(version as i64)
        .build();

    docker.update_config("my-config", spec, options).await
};
Source§

impl Docker

Source

pub async fn list_containers( &self, options: Option<ListContainersOptions>, ) -> Result<Vec<ContainerSummary>, Error>


§List Containers

Returns a list of containers.

§Arguments
§Returns
§Examples
use bollard::query_parameters::ListContainersOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("health".to_string(), vec!["unhealthy".to_string()]);

let options = ListContainersOptionsBuilder::default()
    .all(true)
    .filters(&filters)
    .build();

docker.list_containers(Some(options));
Source

pub async fn create_container( &self, options: Option<CreateContainerOptions>, config: ContainerCreateBody, ) -> Result<ContainerCreateResponse, Error>


§Create Container

Prepares a container for a subsequent start operation.

§Arguments
§Returns
§Examples
use bollard::query_parameters::CreateContainerOptionsBuilder;
use bollard::models::ContainerCreateBody;

let options = CreateContainerOptionsBuilder::default()
    .name("my-new-container")
    .build();

let config = ContainerCreateBody {
    image: Some("hello-world".to_string()),
    cmd: Some(vec!["/hello".to_string()]),
    ..Default::default()
};

docker.create_container(Some(options), config);
Source

pub async fn start_container( &self, container_name: &str, options: Option<StartContainerOptions>, ) -> Result<(), Error>


§Start Container

Starts a container, after preparing it with the Create Container API.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.start_container("hello-world", None);
Source

pub async fn stop_container( &self, container_name: &str, options: Option<StopContainerOptions>, ) -> Result<(), Error>


§Stop Container

Stops a container.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::StopContainerOptionsBuilder;

let options = StopContainerOptionsBuilder::default()
    .t(30)
    .build();

docker.stop_container("hello-world", Some(options));
Source

pub async fn remove_container( &self, container_name: &str, options: Option<RemoveContainerOptions>, ) -> Result<(), Error>


§Remove Container

Remove a container.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::RemoveContainerOptionsBuilder;

let options = RemoveContainerOptionsBuilder::default()
    .force(true)
    .build();

docker.remove_container("hello-world", Some(options));
Source

pub fn wait_container( &self, container_name: &str, options: Option<WaitContainerOptions>, ) -> impl Stream<Item = Result<ContainerWaitResponse, Error>>


§Wait Container

Wait for a container to stop. This is a non-blocking operation, the resulting stream will end when the container stops.

§Arguments
§Returns
§Examples
use bollard::query_parameters::WaitContainerOptionsBuilder;

let options = WaitContainerOptionsBuilder::default()
    .condition("not-running")
    .build();

docker.wait_container("hello-world", Some(options));
Source

pub async fn attach_container( &self, container_name: &str, options: Option<AttachContainerOptions>, ) -> Result<AttachContainerResults, Error>


§Attach Container

Attach to a container to read its output or send it input. You can attach to the same container multiple times and you can reattach to containers that have been detached.

§Arguments
§Returns
§Examples
use bollard::query_parameters::AttachContainerOptionsBuilder;

let options = AttachContainerOptionsBuilder::default()
    .stdin(true)
    .stdout(true)
    .stderr(true)
    .stream(true)
    .logs(true)
    .detach_keys("ctrl-c")
    .build();

docker.attach_container("hello-world", Some(options));
Source

pub async fn resize_container_tty( &self, container_name: &str, options: ResizeContainerTTYOptions, ) -> Result<(), Error>


§Resize container tty

Resize the container’s TTY.

§Arguments
§Examples
use bollard::query_parameters::ResizeContainerTTYOptionsBuilder;

let options = ResizeContainerTTYOptionsBuilder::default()
    .w(50)
    .h(20)
    .build();

docker.resize_container_tty("hello-world", options);
Source

pub async fn restart_container( &self, container_name: &str, options: Option<RestartContainerOptions>, ) -> Result<(), Error>


§Restart Container

Restart a container.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::RestartContainerOptionsBuilder;

let options = RestartContainerOptionsBuilder::default()
    .t(30)
    .build();

docker.restart_container("postgres", Some(options));
Source

pub async fn inspect_container( &self, container_name: &str, options: Option<InspectContainerOptions>, ) -> Result<ContainerInspectResponse, Error>


§Inspect Container

Inspect a container.

§Arguments
§Returns
§Examples
use bollard::query_parameters::InspectContainerOptionsBuilder;

let options = InspectContainerOptionsBuilder::default()
    .size(false)
    .build();

docker.inspect_container("hello-world", Some(options));
Source

pub async fn get_container_archive_info( &self, container_name: &str, options: Option<ContainerArchiveInfoOptions>, ) -> Result<PathStatResponse, Error>


§Get Archive information From Container

Get information on an archive of a resource in the filesystem of container id.

§Arguments
§Returns
§Examples
use bollard::query_parameters::ContainerArchiveInfoOptionsBuilder;

let options = ContainerArchiveInfoOptionsBuilder::default().path("/example").build();

docker.get_container_archive_info("my-container", Some(options));
Source

pub async fn top_processes( &self, container_name: &str, options: Option<TopOptions>, ) -> Result<ContainerTopResponse, Error>


§Top Processes

List processes running inside a container.

§Arguments
  • Container name as string slice.
  • Optional Top Options struct.
§Returns
§Examples
use bollard::query_parameters::TopOptionsBuilder;

let options = TopOptionsBuilder::default()
    .ps_args("aux")
    .build();

docker.top_processes("fussybeaver/uhttpd", Some(options));
Source

pub fn logs( &self, container_name: &str, options: Option<LogsOptions>, ) -> impl Stream<Item = Result<LogOutput, Error>>


§Logs

Get container logs.

§Arguments
  • Container name as string slice.
  • Optional Logs Options struct.
§Returns
§Examples
use bollard::query_parameters::LogsOptionsBuilder;

let options = LogsOptionsBuilder::default()
    .stdout(true)
    .build();

docker.logs("hello-world", Some(options));
Source

pub async fn container_changes( &self, container_name: &str, ) -> Result<Option<Vec<FilesystemChange>>, Error>


§Container Changes

Get changes on a container’s filesystem.

§Arguments
  • Container name as string slice.
§Returns
§Examples

docker.container_changes("hello-world");
Source

pub fn stats( &self, container_name: &str, options: Option<StatsOptions>, ) -> impl Stream<Item = Result<ContainerStatsResponse, Error>>


§Stats

Get container stats based on resource usage.

§Arguments
§Returns
§Examples
use bollard::query_parameters::StatsOptionsBuilder;

let options = StatsOptionsBuilder::default()
    .stream(false)
    .one_shot(true)
    .build();

docker.stats("hello-world", Some(options));
Source

pub async fn kill_container( &self, container_name: &str, options: Option<KillContainerOptions>, ) -> Result<(), Error>


§Kill Container

Kill a container.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::KillContainerOptionsBuilder;

let options = KillContainerOptionsBuilder::default()
    .signal("SIGINT")
    .build();

docker.kill_container("postgres", Some(options));
Source

pub async fn update_container( &self, container_name: &str, config: ContainerUpdateBody, ) -> Result<(), Error>


§Update Container

Update a container.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::models::ContainerUpdateBody;

let config = ContainerUpdateBody {
    memory: Some(314572800),
    memory_swap: Some(314572800),
    ..Default::default()
};

docker.update_container("postgres", config);
Source

pub async fn rename_container( &self, container_name: &str, options: RenameContainerOptions, ) -> Result<(), Error>


§Rename Container

Rename a container.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::RenameContainerOptionsBuilder;

let options = RenameContainerOptionsBuilder::default()
    .name("my_new_container_name")
    .build();

docker.rename_container("hello-world", options);
Source

pub async fn pause_container(&self, container_name: &str) -> Result<(), Error>


§Pause Container

Use the cgroups freezer to suspend all processes in a container.

§Arguments
  • Container name as a string slice.
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.pause_container("postgres");
Source

pub async fn unpause_container(&self, container_name: &str) -> Result<(), Error>


§Unpause Container

Resume a container which has been paused.

§Arguments
  • Container name as a string slice.
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.unpause_container("postgres");
Source

pub async fn prune_containers( &self, options: Option<PruneContainersOptions>, ) -> Result<ContainerPruneResponse, Error>


§Prune Containers

Delete stopped containers.

§Arguments
§Returns
§Examples
use bollard::query_parameters::PruneContainersOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("until".to_string(), vec!["10m".to_string()]);

let options = PruneContainersOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.prune_containers(Some(options));
Source

pub async fn upload_to_container_streaming( &self, container_name: &str, options: Option<UploadToContainerOptions>, tar: impl Stream<Item = Bytes> + Send + 'static, ) -> Result<(), Error>

👎Deprecated since 0.19.0:

This method is refactored into upload_to_container


§Stream Upload To Container

Stream an upload of a tar archive to be extracted to a path in the filesystem of container id.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::UploadToContainerOptionsBuilder;
use futures_util::{StreamExt, TryFutureExt};
use tokio::fs::File;
use tokio_util::io::ReaderStream;

let options = UploadToContainerOptionsBuilder::default()
    .path("/opt")
    .build();

let file = File::open("tarball.tar.gz")
    .map_ok(ReaderStream::new)
    .try_flatten_stream()
    .map(|x|x.expect("failed to stream file"));

docker
    .upload_to_container_streaming("my-container", Some(options), file)
    .await
    .expect("upload failed");
Source

pub async fn upload_to_container( &self, container_name: &str, options: Option<UploadToContainerOptions>, tar: Either<Full<Bytes>, StreamBody<Pin<Box<dyn Stream<Item = Result<Frame<Bytes>, Error>> + Send>>>>, ) -> Result<(), Error>


§Upload To Container

Upload a tar archive to be extracted to a path in the filesystem of container id.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples

Uploading a tarball

use bollard::query_parameters::UploadToContainerOptionsBuilder;
use bollard::body_full;
use std::fs::File;
use std::io::Read;

let options = UploadToContainerOptionsBuilder::default()
    .path("/opt")
    .build();

let mut file = File::open("tarball.tar.gz").unwrap();
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();

docker
    .upload_to_container("my-container", Some(options), body_full(contents.into()))
    .await
    .expect("upload failed");

Uploading a stream

use bollard::query_parameters::UploadToContainerOptionsBuilder;
use bollard::body_try_stream;
use futures_util::{StreamExt, TryFutureExt};
use tokio::fs::File;
use tokio_util::io::ReaderStream;

let options = UploadToContainerOptionsBuilder::default()
    .path("/opt")
    .build();

let file = File::open("tarball.tar.gz")
    .map_ok(ReaderStream::new)
    .try_flatten_stream();

docker
    .upload_to_container("my-container", Some(options), body_try_stream(file))
    .await
    .expect("upload failed");
Source

pub fn download_from_container( &self, container_name: &str, options: Option<DownloadFromContainerOptions>, ) -> impl Stream<Item = Result<Bytes, Error>>


§Download From Container

Get a tar archive of a resource in the filesystem of container id.

§Arguments
§Returns
  • Tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. Hyper Body.
§Examples
use bollard::query_parameters::DownloadFromContainerOptionsBuilder;

let options = DownloadFromContainerOptionsBuilder::default()
    .path("/opt")
    .build();

docker.download_from_container("my-container", Some(options));
Source

pub fn export_container( &self, container_name: &str, ) -> impl Stream<Item = Result<Bytes, Error>>


§Export Container

Get a tarball containing the filesystem contents of a container.

See the Docker API documentation for more information.

§Arguments
  • The container_name string referring to an individual container
§Returns
  • An uncompressed TAR archive
Source

pub async fn create_checkpoint( &self, container_name: &str, options: CreateCheckpointOptions, ) -> Result<(), Error>


§Create Checkpoint

Create a checkpoint from a running container.

This is an experimental feature that requires:

  • Docker daemon with experimental features enabled
  • CRIU installed on the host (Linux only)
§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::container::CreateCheckpointOptions;

let options = CreateCheckpointOptions {
    checkpoint_id: String::from("my-checkpoint"),
    exit: true,
    ..Default::default()
};

docker.create_checkpoint("my-container", options);
Source

pub async fn list_checkpoints( &self, container_name: &str, options: Option<ListCheckpointsOptions>, ) -> Result<Vec<Checkpoint>, Error>


§List Checkpoints

List checkpoints for a container.

See create_checkpoint for experimental feature requirements.

§Arguments
§Returns
  • Vector of Checkpoint structs, wrapped in a Future.
§Examples
use bollard::container::ListCheckpointsOptions;

docker.list_checkpoints("my-container", None::<ListCheckpointsOptions>);
Source

pub async fn delete_checkpoint( &self, container_name: &str, checkpoint_id: &str, options: Option<DeleteCheckpointOptions>, ) -> Result<(), Error>


§Delete Checkpoint

Delete a checkpoint from a container.

See create_checkpoint for experimental feature requirements.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::container::DeleteCheckpointOptions;

docker.delete_checkpoint("my-container", "my-checkpoint", None::<DeleteCheckpointOptions>);
Source§

impl Docker

A Docker implementation typed to connect to a secure HTTPS connection using the rustls library.

Source

pub fn connect_with_ssl_defaults() -> Result<Docker, Error>

Connect using secure HTTPS using defaults that are signalled by environment variables.

§Defaults
  • The connection url is sourced from the DOCKER_HOST environment variable.
  • The certificate directory is sourced from the DOCKER_CERT_PATH environment variable.
  • Certificates are named key.pem, cert.pem and ca.pem to indicate the private key, the server certificate and the certificate chain respectively.
  • The request timeout defaults to 2 minutes.
§Examples
use bollard::Docker;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_ssl_defaults().unwrap();
connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
§Panics

This function will panic if neither ssl nor aws-lc-rs features are activated, or if you are using the ssl_providerless feature without installing the custom cryptographic provider before with rustls::crypto::CryptoProvider::install_default()

Source

pub fn connect_with_ssl( addr: &str, ssl_key: &Path, ssl_cert: &Path, ssl_ca: &Path, timeout: u64, client_version: &ClientVersion, ) -> Result<Docker, Error>

Connect using secure HTTPS.

§Arguments
  • addr: the connection url.
  • ssl_key: the private key path.
  • ssl_cert: the server certificate path.
  • ssl_ca: the certificate chain path.
  • timeout: the read/write timeout (seconds) to use for every hyper connection
  • client_version: the client version to communicate with the server.
§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use std::path::Path;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_ssl(
    "tcp://localhost:2375/",
    Path::new("/certs/key.pem"),
    Path::new("/certs/cert.pem"),
    Path::new("/certs/ca.pem"),
    120,
    API_DEFAULT_VERSION).unwrap();
connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
§Panics

This function will panic if neither ssl nor aws-lc-rs features are activated, or if you are using the ssl_providerless feature without installing the custom cryptographic provider before with rustls::crypto::CryptoProvider::install_default()

Source§

impl Docker

A Docker implementation typed to connect to an unsecure Http connection.

Source

pub fn connect_with_http_defaults() -> Result<Docker, Error>

Connect using unsecured HTTP using defaults that are signalled by environment variables.

§Defaults
  • The connection url is sourced from the DOCKER_HOST environment variable, and defaults to localhost:2375.
  • The number of threads used for the HTTP connection pool defaults to 1.
  • The request timeout defaults to 2 minutes.
§Examples
use bollard::Docker;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_http_defaults().unwrap();
connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_http( addr: &str, timeout: u64, client_version: &ClientVersion, ) -> Result<Docker, Error>

Connect using unsecured HTTP.

§Arguments
  • addr: connection url including scheme and port.
  • timeout: the read/write timeout (seconds) to use for every hyper connection
  • client_version: the client version to communicate with the server.
§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_http(
                   "http://my-custom-docker-server:2735", 4, API_DEFAULT_VERSION)
                   .unwrap();
connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source§

impl Docker

A Docker implementation typed to custom connector.

Source

pub fn connect_with_custom_transport<S: Into<String>>( transport: impl CustomTransport + 'static, client_addr: Option<S>, timeout: u64, client_version: &ClientVersion, ) -> Result<Docker, Error>

Connect using custom transport implementation. It has default implementation for Fn(Request) -> Future<Output = Result<Response<hyper::body::Incoming>, Error>> + Send + Sync

§Arguments
  • transport: transport.
  • timeout: the read/write timeout (seconds) to use for every hyper connection
  • client_version: the client version to communicate with the server.
§Examples
use bollard::{API_DEFAULT_VERSION, Docker, BollardRequest};
use futures_util::future::TryFutureExt;
use futures_util::FutureExt;

let http_connector = hyper_util::client::legacy::connect::HttpConnector::new();

let mut client_builder = hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
client_builder.pool_max_idle_per_host(0);

let client = std::sync::Arc::new(client_builder.build(http_connector));

let connection = Docker::connect_with_custom_transport(
    move |req: BollardRequest| {
        let client = std::sync::Arc::clone(&client);
        Box::pin(async move {
            let (p, b) = req.into_parts();
            // let _prev = p.headers.insert("host", host);
            // let mut uri = p.uri.into_parts();
            //uri.path_and_query = uri.path_and_query.map(|paq|
            //   uri::PathAndQuery::try_from("/docker".to_owned() + paq.as_str())
            // ).transpose().map_err(bollard::errors::Error::from)?;
            // p.uri = uri.try_into().map_err(bollard::errors::Error::from)?;
            let req = BollardRequest::from_parts(p, b);
            client.request(req).await.map_err(bollard::errors::Error::from)
        })
    },
    Some("http://my-custom-docker-server:2735"),
    4,
    bollard::API_DEFAULT_VERSION,
).unwrap();

connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source§

impl Docker

A Docker implementation that wraps away which local implementation we are calling.

Source

pub fn connect_with_socket_defaults() -> Result<Docker, Error>

Connect using to either a Unix socket or a Windows named pipe using defaults common to the standard docker configuration.

§Defaults
  • The unix socket location defaults to /var/run/docker.sock. The windows named pipe location defaults to //./pipe/docker_engine.
  • The request timeout defaults to 2 minutes.
§Examples
use bollard::Docker;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_socket_defaults().unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_socket( path: &str, timeout: u64, client_version: &ClientVersion, ) -> Result<Docker, Error>

Connect using a Unix socket or a Windows named pipe.

§Arguments
  • path: connection unix socket path or windows named pipe path.
  • timeout: the read/write timeout (seconds) to use for every hyper connection
  • client_version: the client version to communicate with the server.
§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_socket("/var/run/docker.sock", 120, API_DEFAULT_VERSION).unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_local_defaults() -> Result<Docker, Error>

Connect using the local machine connection method with default arguments.

Delegates to Docker::connect_with_unix_defaults on Unix or connect_with_named_pipe_defaults on Windows.

To connect to Podman instead, use Docker::connect_with_podman_defaults.

Source

pub fn connect_with_local( addr: &str, timeout: u64, client_version: &ClientVersion, ) -> Result<Docker, Error>

Connect using the local machine connection method with supplied arguments.

This is a simple wrapper over the OS specific handlers:

Source§

impl Docker

A Docker implementation with defaults.

Source

pub fn connect_with_defaults() -> Result<Docker, Error>

Connect using a Unix socket, a Windows named pipe, or via HTTP. The connection method is determined by the DOCKER_HOST environment variable.

§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_defaults().unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_host(host: &str) -> Result<Docker, Error>

Connect using a Unix socket, a Windows named pipe, or via HTTP. The connection method is determined by host parameter.

§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_host("unix:///var/run/docker.sock").unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source§

impl Docker

A Docker implementation typed to connect to a Unix socket.

Source

pub fn connect_with_unix_defaults() -> Result<Docker, Error>

Connect using a Unix socket using defaults common to the standard docker configuration.

§Defaults
  • The socket location defaults to the value of DEFAULT_SOCKET env if its set and the URL has unix scheme; otherwise /var/run/docker.sock.
  • The request timeout defaults to 2 minutes.
§Examples
use bollard::Docker;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_unix_defaults().unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_podman_defaults() -> Result<Docker, Error>

Connect to a Podman socket with default arguments.

§Socket discovery order
  1. $DOCKER_HOST — if set and starts with unix://, used directly.
  2. Rootless Podman: $XDG_RUNTIME_DIR/podman/podman.sock
  3. Rootless Podman: /run/user/$UID/podman/podman.sock
  4. System Podman: /run/podman/podman.sock
  5. Falls back to the default Docker socket (/var/run/docker.sock).
§Examples
use bollard::Docker;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_podman_defaults().unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_unix( path: &str, timeout: u64, client_version: &ClientVersion, ) -> Result<Docker, Error>

Connect using a Unix socket.

§Arguments
  • addr: connection socket path.
  • timeout: the read/write timeout (seconds) to use for every hyper connection
  • client_version: the client version to communicate with the server.
§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_unix("/var/run/docker.sock", 120, API_DEFAULT_VERSION).unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source§

impl Docker

A Docker implementation typed to connect to an SSH connection.

Source

pub fn connect_with_ssh_defaults() -> Result<Docker, Error>

Connect using SSH using defaults that are signalled by environment variables.

§Defaults
  • The connection url is sourced from the DOCKER_HOST environment variable, and defaults to ssh://localhost.
  • The number of threads used for the HTTP connection pool defaults to 1.
  • The request timeout defaults to 2 minutes.
§Examples
use bollard::Docker;

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_ssh_defaults().unwrap();
connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source

pub fn connect_with_ssh( addr: &str, timeout: u64, client_version: &ClientVersion, keypair_path: Option<String>, ) -> Result<Docker, Error>

Connect using SSH.

§Arguments
  • addr: connection url including scheme and port.
  • timeout: the read/write timeout (seconds) to use for every hyper connection
  • client_version: the client version to communicate with the server.
§Examples
use bollard::{API_DEFAULT_VERSION, Docker};

use futures_util::future::TryFutureExt;

let connection = Docker::connect_with_ssh(
                   "ssh://user@my-custom-docker-server", 4, API_DEFAULT_VERSION, None)
                   .unwrap();
connection.ping()
  .map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Source§

impl Docker

Source

pub fn with_timeout(self, timeout: Duration) -> Self

Set the request timeout.

This timeout is shared by all requests to the Docker Engine API.

By default, 2 minutes.

Source

pub fn timeout(&self) -> Duration

Get the current timeout.

This timeout is shared by all requests to the Docker Engine API.

Source

pub fn set_timeout(&mut self, timeout: Duration)

Set the request timeout.

This timeout is shared by all requests to the Docker Engine API.

By default, 2 minutes.

Source

pub fn with_request_modifier<F>(self, modifier: F) -> Self
where F: Fn(BollardRequest) -> BollardRequest + Send + Sync + 'static,

Set a request modifier callback that runs before each request.

This callback can modify the request before it is sent to the Docker Engine API. Useful for setting User-Agent headers or other request modifications.

§Example
use bollard::Docker;
use http::header::{HeaderValue, USER_AGENT};

let docker = Docker::connect_with_socket_defaults()
    .unwrap()
    .with_request_modifier(|mut req| {
        req.headers_mut().insert(USER_AGENT, HeaderValue::from_static("my-app/1.0"));
        req
    });
Source§

impl Docker

Source

pub fn client_version(&self) -> ClientVersion

Return the currently set client version.

Source

pub async fn negotiate_version(self) -> Result<Self, Error>

Check with the server for a supported version, and downgrade the client version if appropriate.

§Examples:
    use bollard::Docker;

    let docker = Docker::connect_with_http_defaults().unwrap();
    async move {
        &docker.negotiate_version().await.unwrap().version();
    };
Source§

impl Docker

Source

pub async fn create_exec( &self, container_name: &str, config: impl Into<ExecConfig>, ) -> Result<CreateExecResults, Error>


§Create Exec

Run a command inside a running container.

§Arguments
§Returns
§Examples

use bollard::exec::CreateExecOptions;

use std::default::Default;

let config = CreateExecOptions {
    cmd: Some(vec!["ps", "-ef"]),
    attach_stdout: Some(true),
    ..Default::default()
};

docker.create_exec("hello-world", config);
Source

pub async fn start_exec( &self, exec_id: &str, config: Option<StartExecOptions>, ) -> Result<StartExecResults, Error>


§Start Exec

Starts a previously set up exec instance. If detach is true, this endpoint returns immediately after starting the command.

§Arguments
  • The ID of the previously created exec configuration.
§Returns
§Examples



async {
    let message = docker.create_exec("hello-world", config).await.unwrap();
    use bollard::exec::StartExecOptions;
    docker.start_exec(&message.id, None::<StartExecOptions>);
};
Source

pub async fn inspect_exec( &self, exec_id: &str, ) -> Result<ExecInspectResponse, Error>


§Inspect Exec

Return low-level information about an exec instance.

§Arguments
  • The ID of the previously created exec configuration.
§Returns
§Examples



async {
    let message = docker.create_exec("hello-world", config).await.unwrap();
    docker.inspect_exec(&message.id);
};
Source

pub async fn resize_exec( &self, exec_id: &str, options: impl Into<ResizeExecOptions>, ) -> Result<(), Error>


§Resize Exec

Resize the TTY session used by an exec instance. This endpoint only works if tty was specified as part of creating and starting the exec instance.

§Arguments
§Examples
async {
    let message = docker.create_exec("hello-world", config).await.unwrap();
    docker.resize_exec(&message.id, ResizeExecOptions {
        width: 80,
        height: 60
    });
};
Source§

impl Docker

Source

pub async fn list_images( &self, options: Option<impl Into<ListImagesOptions>>, ) -> Result<Vec<ImageSummary>, Error>


§List Images

Returns a list of images on the server. Note that it uses a different, smaller representation of an image than inspecting a single image

§Arguments
§Returns
§Examples
use bollard::query_parameters::ListImagesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("dangling", vec!["true"]);

let options = ListImagesOptionsBuilder::default()
    .all(true)
    .filters(&filters)
    .build();

docker.list_images(Some(options));
Source

pub fn create_image( &self, options: Option<impl Into<CreateImageOptions>>, root_fs: Option<Either<Full<Bytes>, StreamBody<Pin<Box<dyn Stream<Item = Result<Frame<Bytes>, Error>> + Send>>>>>, credentials: Option<DockerCredentials>, ) -> impl Stream<Item = Result<CreateImageInfo, Error>>


§Create Image

Create an image by either pulling it from a registry or importing it.

§Arguments
  • An optional Create Image Options struct.
  • An optional request body consisting of a tar or tar.gz archive, or a stream containing the root file system for the image. If this argument is used, the value of the from_src option must be “-”.
§Returns
§Examples
use bollard::query_parameters::CreateImageOptionsBuilder;

let options = CreateImageOptionsBuilder::default()
    .from_image("hello-world")
    .build();

docker.create_image(Some(options), None, None);

// do some other work while the image is pulled from the docker hub...
§Unsupported
  • Import from tarball
Source

pub async fn inspect_image( &self, image_name: &str, ) -> Result<ImageInspect, Error>


§Inspect Image

Return low-level information about an image.

§Arguments
  • Image name as a string slice.
§Returns
§Examples

use std::default::Default;

docker.inspect_image("hello-world");
Source

pub async fn inspect_registry_image( &self, image_name: &str, credentials: Option<DockerCredentials>, ) -> Result<DistributionInspect, Error>


§Inspect an Image by contacting the registry

Return image digest and platform information by contacting the registry

§Arguments
  • Image name as a string slice.
§Returns
§Examples
use bollard::Docker;
let docker = Docker::connect_with_http_defaults().unwrap();
docker.inspect_registry_image("ubuntu:jammy", None);
Source

pub async fn prune_images( &self, options: Option<impl Into<PruneImagesOptions>>, ) -> Result<ImagePruneResponse, Error>


§Prune Images

Delete unused images.

§Arguments
§Returns
§Examples
use bollard::query_parameters::PruneImagesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("until", vec!["10m"]);

let options = PruneImagesOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.prune_images(Some(options));
Source

pub async fn image_history( &self, image_name: &str, ) -> Result<Vec<ImageHistoryResponseItem>, Error>


§Image History

Return parent layers of an image.

§Arguments
  • Image name as a string slice.
§Returns
§Examples

docker.image_history("hello-world");
Source

pub async fn search_images( &self, options: impl Into<SearchImagesOptions>, ) -> Result<Vec<ImageSearchResponseItem>, Error>


§Search Images

Search for an image on Docker Hub.

§Arguments
§Returns
§Examples
use bollard::query_parameters::SearchImagesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("until", vec!["10m"]);

let search_options = SearchImagesOptionsBuilder::default()
    .term("hello-world")
    .filters(&filters)
    .build();

docker.search_images(search_options);
Source

pub async fn remove_image( &self, image_name: &str, options: Option<impl Into<RemoveImageOptions>>, credentials: Option<DockerCredentials>, ) -> Result<Vec<ImageDeleteResponseItem>, Error>


§Remove Image

Remove an image, along with any untagged parent images that were referenced by that image.

§Arguments
§Returns
§Examples
use bollard::query_parameters::RemoveImageOptionsBuilder;

let remove_options = RemoveImageOptionsBuilder::default()
    .force(true)
    .build();

docker.remove_image("hello-world", Some(remove_options), None);
Source

pub async fn tag_image( &self, image_name: &str, options: Option<impl Into<TagImageOptions>>, ) -> Result<(), Error>


§Tag Image

Tag an image so that it becomes part of a repository.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::TagImageOptionsBuilder;

let tag_options = TagImageOptionsBuilder::default()
    .tag("v1.0.1")
    .build();

docker.tag_image("hello-world", Some(tag_options));
Source

pub fn push_image( &self, image_name: &str, options: Option<impl Into<PushImageOptions>>, credentials: Option<DockerCredentials>, ) -> impl Stream<Item = Result<PushImageInfo, Error>>


§Push Image

Push an image to a registry.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::auth::DockerCredentials;
use bollard::query_parameters::PushImageOptionsBuilder;

let push_options = PushImageOptionsBuilder::default()
    .tag("v1.0.1")
    .build();

let credentials = Some(DockerCredentials {
    username: Some("Jack".to_string()),
    password: Some("myverysecretpassword".to_string()),
    ..Default::default()
});

docker.push_image("hello-world", Some(push_options), credentials);
Source

pub async fn commit_container( &self, options: impl Into<CommitContainerOptions>, config: impl Into<ContainerConfig>, ) -> Result<IdResponse, Error>


§Commit Container

Create a new image from a container.

§Arguments
§Returns
  • Commit, wrapped in a Future.
§Examples
use bollard::query_parameters::CommitContainerOptionsBuilder;
use bollard::models::ContainerConfig;

let options = CommitContainerOptionsBuilder::default()
    .container("my-running-container")
    .pause(true)
    .build();

let config = ContainerConfig {
    ..Default::default()
};

docker.commit_container(options, config);
Source

pub fn build_image( &self, options: impl Into<BuildImageOptions>, credentials: Option<HashMap<String, DockerCredentials>>, tar: Option<Either<Full<Bytes>, StreamBody<Pin<Box<dyn Stream<Item = Result<Frame<Bytes>, Error>> + Send>>>>>, ) -> impl Stream<Item = Result<BuildInfo, Error>> + '_


§Build Image

Build an image from a tar archive with a Dockerfile in it.

The Dockerfile specifies how the image is built from the tar archive. It is typically in the archive’s root, but can be at a different path or have a different name by specifying the dockerfile parameter.

By default, the call to build specifies using BuilderV1, the first generation builder in docker daemon.

§Arguments
§Returns
§Examples

Sending a tarball:

use bollard::query_parameters::BuildImageOptionsBuilder;
use bollard::body_full;

use std::fs::File;
use std::io::Read;

let options = BuildImageOptionsBuilder::default()
    .dockerfile("Dockerfile")
    .t("my-image")
    .rm(true)
    .build();

let mut file = File::open("tarball.tar.gz").unwrap();
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();

docker.build_image(options, None, Some(body_full(contents.into())));

Sending a stream:

use bollard::query_parameters::BuildImageOptionsBuilder;
use bollard::body_stream;

use std::fs::File;
use std::io::Read;

let options = BuildImageOptionsBuilder::default()
    .dockerfile("Dockerfile")
    .t("my-image")
    .rm(true)
    .build();


docker.build_image(options, None, Some(body_stream(stream)));
Source

pub async fn prune_build( &self, options: Option<impl Into<PruneBuildOptions>>, ) -> Result<BuildPruneResponse, Error>


§Prune Build

Delete contents of the build cache

§Arguments
§Returns
§Examples
use bollard::query_parameters::PruneBuildOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("until", vec!["10m"]);

let options = PruneBuildOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.prune_build(Some(options));
Source

pub fn export_image( &self, image_name: &str, ) -> impl Stream<Item = Result<Bytes, Error>>


§Export Image

Get a tarball containing all images and metadata for a repository.

The root of the resulting tar file will contain the file “manifest.json”. If the export is of an image repository, rather than a single image, there will also be a repositories file with a JSON description of the exported image repositories. Additionally, each layer of all exported images will have a sub directory in the archive containing the filesystem of the layer.

See the Docker API documentation for more information.

§Arguments
  • The image_name string referring to an individual image and tag (e.g. alpine:latest)
§Returns
  • An uncompressed TAR archive
Source

pub fn export_images( &self, image_names: &[&str], ) -> impl Stream<Item = Result<Bytes, Error>>


§Export Images

Get a tarball containing all images and metadata for several image repositories. Shared layers will be deduplicated.

See the Docker API documentation for more information.

§Arguments
  • The image_names Vec of image names.
§Returns
  • An uncompressed TAR archive
Source

pub fn import_image( &self, options: impl Into<ImportImageOptions>, root_fs: Either<Full<Bytes>, StreamBody<Pin<Box<dyn Stream<Item = Result<Frame<Bytes>, Error>> + Send>>>>, credentials: Option<HashMap<String, DockerCredentials>>, ) -> impl Stream<Item = Result<BuildInfo, Error>>


§Import Image

Load a set of images and tags into a repository.

For details on the format, see the export image endpoint.

§Arguments
§Returns
§Examples
use bollard::query_parameters::ImportImageOptionsBuilder;
use bollard::errors::Error;
use bollard::body_full;

use futures_util::stream::{StreamExt, TryStreamExt};
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tokio_util::codec;

let options = ImportImageOptionsBuilder::default()
    .build();

async move {
    let mut file = File::open("tarball.tar.gz").await.unwrap();

    let mut byte_stream = codec::FramedRead::new(file, codec::BytesCodec::new()).map(|r| {
        let bytes = r.unwrap().freeze();
        Ok::<_, Error>(bytes)
    });

    let bytes = byte_stream.next().await.unwrap().unwrap();

    let mut stream = docker
        .import_image(
            ImportImageOptionsBuilder::default().build(),
            body_full(bytes),
            None,
        );

    while let Some(response) = stream.next().await {
        // ...
    }
};
Source

pub fn import_image_stream<S, E>( &self, options: impl Into<ImportImageOptions>, root_fs: S, credentials: Option<HashMap<String, DockerCredentials>>, ) -> impl Stream<Item = Result<BuildInfo, Error>>
where S: Stream<Item = Result<Bytes, E>> + Send + 'static, E: Into<Box<dyn Error + Send + Sync>> + 'static,


§Import Image (stream)

Load a set of images and tags into a repository, without holding it all in memory at a given point in time

For details on the format, see the export image endpoint.

§Arguments
§Returns
§Examples
use bollard::query_parameters::ImportImageOptionsBuilder;
use bollard::errors::Error;

use futures_util::stream::{StreamExt, TryStreamExt};
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tokio_util::codec;

let options = ImportImageOptionsBuilder::default()
    .build();

async move {
    let mut file = File::open("tarball.tar.gz").await.unwrap();

    let mut byte_stream = codec::FramedRead::new(file, codec::BytesCodec::new()).map(|r| {
        r.map(|b| b.freeze())
    });

    let mut stream = docker
        .import_image_stream(
            ImportImageOptionsBuilder::default().build(),
            byte_stream,
            None,
        );

    while let Some(response) = stream.next().await {
        // ...
    }
};
Source§

impl Docker

Source

pub async fn create_network( &self, config: NetworkCreateRequest, ) -> Result<NetworkCreateResponse, Error>


§Create Network

Create a new network.

§Arguments
§Returns
§Examples
use bollard::models::NetworkCreateRequest;

let config = NetworkCreateRequest {
    name: String::from("certs"),
    ..Default::default()
};

docker.create_network(config);
Source

pub async fn remove_network(&self, network_name: &str) -> Result<(), Error>


§Remove a Network
§Arguments
  • Network name as a string slice.
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.remove_network("my_network_name");
Source

pub async fn inspect_network( &self, network_name: &str, options: Option<InspectNetworkOptions>, ) -> Result<NetworkInspect, Error>


§Inspect a Network
§Arguments
§Returns
§Examples
use bollard::query_parameters::InspectNetworkOptionsBuilder;

let options = InspectNetworkOptionsBuilder::default()
    .verbose(true)
    .scope("global")
    .build();

docker.inspect_network("my_network_name", Some(options));
Source

pub async fn list_networks( &self, options: Option<ListNetworksOptions>, ) -> Result<Vec<Network>, Error>


§List Networks
§Arguments
§Returns
  • A vector of Network struct, wrapped in a Future.
§Examples
use bollard::query_parameters::ListNetworksOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("label", vec!["maintainer=some_maintainer"]);

let options = ListNetworksOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_networks(Some(options));
Source

pub async fn connect_network( &self, network_name: &str, config: NetworkConnectRequest, ) -> Result<(), Error>


§Connect Network
§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::models::{NetworkConnectRequest, EndpointSettings, EndpointIpamConfig};

let config = NetworkConnectRequest {
    container: String::from("3613f73ba0e4"),
    endpoint_config: Some(EndpointSettings {
        ipam_config: Some(EndpointIpamConfig {
            ipv4_address: Some(String::from("172.24.56.89")),
            ipv6_address: Some(String::from("2001:db8::5689")),
            ..Default::default()
        }),
        ..Default::default()
    }),
};

docker.connect_network("my_network_name", config);
Source

pub async fn disconnect_network( &self, network_name: &str, config: NetworkDisconnectRequest, ) -> Result<(), Error>


§Disconnect Network
§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::models::NetworkDisconnectRequest;

let config = NetworkDisconnectRequest {
    container: String::from("3613f73ba0e4"),
    force: Some(true),
};

docker.disconnect_network("my_network_name", config);
Source

pub async fn prune_networks( &self, options: Option<PruneNetworksOptions>, ) -> Result<NetworkPruneResponse, Error>


§Prune Networks

Deletes networks which are unused.

§Arguments
§Returns
§Examples
use bollard::query_parameters::PruneNetworksOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("label", vec!["maintainer=some_maintainer"]);

let options = PruneNetworksOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.prune_networks(Some(options));
Source§

impl Docker

Source

pub async fn list_nodes( &self, options: Option<ListNodesOptions>, ) -> Result<Vec<Node>, Error>


§List Nodes
§Arguments
§Returns
  • A vector of Node struct, wrapped in a Future.
§Examples
use bollard::query_parameters::ListNodesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("node.label", vec!["my-node-label"]);

let options = ListNodesOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_nodes(Some(options));
Source

pub async fn inspect_node(&self, node_name: &str) -> Result<Node, Error>


§Inspect a Node
§Arguments
  • Node id or name as a string slice.
§Returns
  • A Models struct, wrapped in a Future.
§Examples

docker.inspect_node("my_node_name");
Source

pub async fn delete_node( &self, node_name: &str, options: Option<DeleteNodeOptions>, ) -> Result<(), Error>


§Delete Node

Delete a node.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::DeleteNodeOptionsBuilder;

let options = DeleteNodeOptionsBuilder::default()
    .force(true)
    .build();

docker.delete_node("my-node", Some(options));
Source

pub async fn update_node( &self, node_id: &str, spec: NodeSpec, options: UpdateNodeOptions, ) -> Result<(), Error>


§Update Node

Update a node.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::UpdateNodeOptionsBuilder;
use bollard::models::{NodeSpec, NodeSpecAvailabilityEnum, NodeSpecRoleEnum};

let spec = NodeSpec {
    availability: Some(NodeSpecAvailabilityEnum::ACTIVE),
    name: Some("my-new-node-name".to_string()),
    role: Some(NodeSpecRoleEnum::MANAGER),
    ..Default::default()
};

let options = UpdateNodeOptionsBuilder::default()
    .version(2)
    .build();

docker.update_node("my-node-id", spec, options);
Source§

impl Docker

Source

pub async fn list_plugins( &self, options: Option<ListPluginsOptions>, ) -> Result<Vec<Plugin>, Error>


§List Plugins

Returns a list of plugins.

§Arguments
§Returns
  • Vector of Plugin, wrapped in a Future.
§Examples
use bollard::query_parameters::ListPluginsOptionsBuilder;

use std::collections::HashMap;
use std::default::Default;

let mut filters = HashMap::new();
filters.insert("capability", vec!["volumedriver"]);

let filters: HashMap<String, Vec<String>> = filters.into_iter().map(|(k, v)| (k.to_string(), v.into_iter().map(String::from).collect())).collect();
let options = ListPluginsOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_plugins(Some(options));
Source

pub async fn inspect_plugin(&self, plugin_name: &str) -> Result<Plugin, Error>


§Inspect Plugin

Inspect a plugin.

§Arguments
  • Plugin name as a string slice.
§Returns
  • Plugin, wrapped in a Future.
§Examples

docker.inspect_plugin("vieux/sshfs:latest");
Source

pub async fn remove_plugin( &self, plugin_name: &str, options: Option<RemovePluginOptions>, ) -> Result<Plugin, Error>


§Remove Plugin

Remove a plugin.

§Arguments
§Returns
  • Plugin, wrapped in a Future.
§Examples
use bollard::query_parameters::RemovePluginOptionsBuilder;

let options = RemovePluginOptionsBuilder::default()
    .force(true)
    .build();

docker.remove_plugin("vieux/sshfs:latest", Some(options));
Source

pub async fn enable_plugin( &self, plugin_name: &str, options: Option<EnablePluginOptions>, ) -> Result<(), Error>


§Enable Plugin

Enable a plugin.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::EnablePluginOptionsBuilder;

let options = EnablePluginOptionsBuilder::default()
    .timeout(30)
    .build();

docker.enable_plugin("vieux/sshfs:latest", Some(options));
Source

pub async fn disable_plugin( &self, plugin_name: &str, options: Option<DisablePluginOptions>, ) -> Result<(), Error>


§Disable Plugin

Disable a plugin.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::DisablePluginOptionsBuilder;

let options = DisablePluginOptionsBuilder::default()
    .force(true)
    .build();

docker.disable_plugin("vieux/sshfs:latest", Some(options));
Source

pub async fn get_plugin_privileges( &self, options: GetPluginPrivilegesOptions, ) -> Result<Vec<PluginPrivilege>, Error>


§Get Plugin Privileges

Get the list of privileges required by a plugin.

§Arguments
§Returns
§Examples
use bollard::query_parameters::GetPluginPrivilegesOptionsBuilder;

let options = GetPluginPrivilegesOptionsBuilder::default()
    .remote("vieux/sshfs:latest")
    .build();

docker.get_plugin_privileges(options);
Source

pub fn install_plugin( &self, options: InstallPluginOptions, privileges: Vec<PluginPrivilege>, credentials: Option<DockerCredentials>, ) -> impl Stream<Item = Result<CreateImageInfo, Error>> + '_


§Install Plugin

Pull and install a plugin from a registry. Returns a stream of progress info.

§Arguments
§Returns
§Examples
use bollard::query_parameters::{GetPluginPrivilegesOptionsBuilder, InstallPluginOptionsBuilder};
use futures_util::stream::TryStreamExt;

// First get the required privileges
let priv_opts = GetPluginPrivilegesOptionsBuilder::default()
    .remote("vieux/sshfs:latest")
    .build();
let privileges = docker.get_plugin_privileges(priv_opts).await?;

// Then install with those privileges
let options = InstallPluginOptionsBuilder::default()
    .remote("vieux/sshfs:latest")
    .name("my-sshfs-plugin")
    .build();

let mut stream = docker.install_plugin(options, privileges, None);
while let Some(info) = stream.try_next().await? {
    println!("{:?}", info);
}
Source

pub async fn create_plugin( &self, options: CreatePluginOptions, tar: Either<Full<Bytes>, StreamBody<Pin<Box<dyn Stream<Item = Result<Frame<Bytes>, Error>> + Send>>>>, ) -> Result<(), Error>


§Create Plugin

Create a plugin from a tar archive containing the rootfs and configuration.

§Arguments
  • CreatePluginOptions struct.
  • Tar archive body containing the plugin rootfs directory and config.json file.
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::CreatePluginOptionsBuilder;
use bollard::body_full;

use std::fs::File;
use std::io::Read;

let options = CreatePluginOptionsBuilder::default()
    .name("my-plugin:latest")
    .build();

let mut file = File::open("plugin.tar.gz").unwrap();
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();

docker.create_plugin(options, body_full(contents.into()));
Source

pub async fn upgrade_plugin( &self, plugin_name: &str, options: UpgradePluginOptions, privileges: Vec<PluginPrivilege>, credentials: Option<DockerCredentials>, ) -> Result<(), Error>


§Upgrade Plugin

Upgrade an existing plugin to a newer version.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::UpgradePluginOptionsBuilder;
use bollard::models::PluginPrivilege;

let options = UpgradePluginOptionsBuilder::default()
    .remote("vieux/sshfs:next")
    .build();

let privileges = vec![PluginPrivilege {
    name: Some("network".to_string()),
    description: Some("Allow access to host network".to_string()),
    value: Some(vec!["host".to_string()]),
}];

docker.upgrade_plugin("vieux/sshfs:latest", options, privileges, None);
Source

pub async fn push_plugin( &self, plugin_name: &str, credentials: Option<DockerCredentials>, ) -> Result<(), Error>


§Push Plugin

Push a plugin to a registry.

§Arguments
  • Plugin name as a string slice.
  • Optional Docker Credentials struct for registry authentication.
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::auth::DockerCredentials;

let credentials = Some(DockerCredentials {
    username: Some("my-username".to_string()),
    password: Some("my-password".to_string()),
    ..Default::default()
});

docker.push_plugin("my-plugin:latest", credentials);
Source

pub async fn set_plugin_config( &self, plugin_name: &str, config: Vec<String>, ) -> Result<(), Error>


§Set Plugin Configuration

Configure a plugin by setting environment variables or other settings.

§Arguments
  • Plugin name as a string slice.
  • Vector of configuration strings in the format “KEY=value”.
§Returns
  • unit type (), wrapped in a Future.
§Examples

let config = vec![
    "DEBUG=1".to_string(),
    "MAX_CONNECTIONS=1000".to_string(),
];

docker.set_plugin_config("vieux/sshfs:latest", config);
Source§

impl Docker

Source

pub async fn list_secrets( &self, options: Option<ListSecretsOptions>, ) -> Result<Vec<Secret>, Error>


§List Secrets

Returns a list of secrets.

§Arguments
§Returns
  • Vector of Secret, wrapped in a Future.
§Examples
use bollard::query_parameters::ListSecretsOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("label", vec!["secret-label=label-value"]);

let options = ListSecretsOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_secrets(Some(options));
Source

pub async fn create_secret( &self, secret_spec: SecretSpec, ) -> Result<IdResponse, Error>


§Create Secret

Create new secret on the docker swarm.

§Arguments
§Returns
§Examples
use bollard::models::SecretSpec;

use base64;

let secret_spec = SecretSpec {
    name: Some(String::from("secret-name")),
    data: Some(base64::engine::general_purpose::STANDARD.encode("secret-data")),
    ..Default::default()
};

docker.create_secret(secret_spec);
Source

pub async fn inspect_secret(&self, secret_id: &str) -> Result<Secret, Error>


§Inspect Secret

Inspect a secret.

§Arguments
  • Secret id or name as a string slice.
§Returns
  • Secret, wrapped in a Future.
§Examples

docker.inspect_secret("secret-id");
docker.inspect_secret("secret-name");
Source

pub async fn delete_secret(&self, secret_id: &str) -> Result<(), Error>


§Delete Secret

Delete a secret, fails when more than one service use that secret..

§Arguments
  • Secret id or name as a string slice.
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.delete_secret("secret-id");
docker.delete_secret("secret-name");
Source

pub async fn update_secret( &self, secret_id: &str, secret_spec: SecretSpec, options: UpdateSecretOptions, ) -> Result<(), Error>


§Update Secret

Update an existing secret, fails when more than one service use that secret or trying update data.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples

use std::collections::HashMap;
use bollard::query_parameters::UpdateSecretOptionsBuilder;

let result = async move {
    let existing = docker.inspect_secret("my-secret").await?;
    let version = existing.version.unwrap().index.unwrap();
    let mut spec = existing.spec.unwrap().clone();

    let mut labels = HashMap::new();
    labels.insert(String::from("secret-label"), String::from("label-value"));
    spec.labels = Some(labels.clone());

    let options = UpdateSecretOptionsBuilder::default()
        .version(version as i64)
        .build();

    docker.update_secret("my-secret", spec, options).await
};
Source§

impl Docker

Source

pub async fn list_services( &self, options: Option<ListServicesOptions>, ) -> Result<Vec<Service>, Error>


§List Services

Returns a list of services.

§Arguments
§Returns
  • Vector of Services, wrapped in a Future.
§Examples
use bollard::query_parameters::ListServicesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("mode", vec!["global"]);

let options = ListServicesOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_services(Some(options));
Source

pub async fn create_service( &self, service_spec: ServiceSpec, credentials: Option<DockerCredentials>, ) -> Result<ServiceCreateResponse, Error>


§Create Service

Dispatch a new service on the docker swarm

§Arguments
§Returns
§Examples
use bollard::service::{
    ServiceSpec,
    ServiceSpecMode,
    ServiceSpecModeReplicated,
    TaskSpec,
    TaskSpecContainerSpec
};

let service = ServiceSpec {
    name: Some(String::from("my-service")),
    mode: Some(ServiceSpecMode {
        replicated: Some(ServiceSpecModeReplicated {
            replicas: Some(2)
        }),
        ..Default::default()
    }),
    task_template: Some(TaskSpec {
        container_spec: Some(TaskSpecContainerSpec {
            image: Some(String::from("hello-world")),
            ..Default::default()
        }),
        ..Default::default()
    }),
    ..Default::default()
};
let credentials = None;

docker.create_service(service, credentials);
Source

pub async fn inspect_service( &self, service_name: &str, options: Option<InspectServiceOptions>, ) -> Result<Service, Error>


§Inspect Service

Inspect a service.

§Arguments
§Returns
§Examples
use bollard::query_parameters::InspectServiceOptionsBuilder;

let options = InspectServiceOptionsBuilder::default()
    .insert_defaults(true)
    .build();

docker.inspect_service("my-service", Some(options));
Source

pub async fn delete_service(&self, service_name: &str) -> Result<(), Error>


§Delete Service

Delete a service.

§Arguments
  • Service name or id as a string slice.
§Returns
  • unit type (), wrapped in a Future.
§Examples

docker.delete_service("my-service");
Source

pub async fn update_service( &self, service_name: &str, service_spec: ServiceSpec, options: UpdateServiceOptions, credentials: Option<DockerCredentials>, ) -> Result<ServiceUpdateResponse, Error>


§Update Service

Update an existing service

§Arguments
§Returns
§Examples
use bollard::query_parameters::UpdateServiceOptionsBuilder;
use bollard::service::{
    ServiceSpec,
    ServiceSpecMode,
    ServiceSpecModeReplicated,
    TaskSpec,
    TaskSpecContainerSpec,
};

use std::default::Default;

let result = async move {
    let service_name = "my-service";
    let current_version = docker.inspect_service(
        service_name,
        None
    ).await?.version.unwrap().index.unwrap();
    let service = ServiceSpec {
        mode: Some(ServiceSpecMode {
            replicated: Some(ServiceSpecModeReplicated {
                replicas: Some(0)
            }),
            ..Default::default()
        }),
        ..Default::default()
    };
    let options = UpdateServiceOptionsBuilder::default()
        .version(current_version as i32)
        .build();
    let credentials = None;

    docker.update_service("my-service", service, options, credentials).await
};
Source

pub fn service_logs( &self, service_id: &str, options: Option<impl Into<LogsOptions>>, ) -> impl Stream<Item = Result<LogOutput, Error>>


§Get Service Logs

Get stdout and stderr logs from a service.

§Arguments
  • Service name or id as a string slice.
  • Optional Logs Options struct.
§Returns
§Examples
use bollard::query_parameters::LogsOptionsBuilder;

let options = LogsOptionsBuilder::default()
    .stdout(true)
    .build();

docker.service_logs("my-service", Some(options));
Source§

impl Docker

Source

pub async fn init_swarm( &self, config: SwarmInitRequest, ) -> Result<String, Error>


§Init Swarm

Initialize a new swarm.

§Arguments
§Returns
  • A String wrapped in a Future.
§Examples
use bollard::models::SwarmInitRequest;

use std::default::Default;

let config = SwarmInitRequest {
    advertise_addr: Some("127.0.0.1".to_string()),
    listen_addr: Some("0.0.0.0:2377".to_string()),
    ..Default::default()
};

docker.init_swarm(config);
Source

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


§Inspect Swarm

Inspect swarm.

§Arguments
§Returns
  • Swarm struct, wrapped in a Future.
§Examples

docker.inspect_swarm();
Source

pub async fn join_swarm(&self, config: SwarmJoinRequest) -> Result<(), Error>


§Join a Swarm
§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::models::SwarmJoinRequest;

let config = SwarmJoinRequest {
    advertise_addr: Some("127.0.0.1".to_string()),
    join_token: Some("token".to_string()),
    ..Default::default()
};
docker.join_swarm(config);
Source

pub async fn leave_swarm( &self, options: Option<LeaveSwarmOptions>, ) -> Result<(), Error>


§Leave a Swarm
§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples

let options = LeaveSwarmOptionsBuilder::default()
    .force(true)
    .build();

docker.leave_swarm(Some(options));
Source

pub async fn update_swarm( &self, swarm_spec: SwarmSpec, options: UpdateSwarmOptions, ) -> Result<(), Error>


§Update a Swarm

Update a swarm’s configuration.

§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples
use bollard::query_parameters::UpdateSwarmOptionsBuilder;

let result = async move {
    let swarm = docker.inspect_swarm().await?;
    let version = swarm.version.unwrap().index.unwrap();
    let spec = swarm.spec.unwrap();

    let options = UpdateSwarmOptionsBuilder::default()
        .version(version as i64)
        .build();

    docker.update_swarm(spec, options).await
};
Source§

impl Docker

Source

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


§Version

Returns the version of Docker that is running and various information about the system that Docker is running on.

§Returns
§Examples
docker.version();
Source

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


§Info

Returns Docker client and server information that is running.

§Returns
  • Info, wrapped in a Future.
§Examples
docker.info();
Source

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


§Ping

This is a dummy endpoint you can use to test if the server is accessible.

§Returns - A String, wrapped in a Future. # Examples

docker.ping();
Source

pub fn events( &self, options: Option<EventsOptions>, ) -> impl Stream<Item = Result<EventMessage, Error>>


§Events

Stream real-time events from the server.

§Returns
§Examples
use bollard::query_parameters::EventsOptionsBuilder;
use std::collections::HashMap;


let mut filters = HashMap::new();
filters.insert("type", vec!["container"]);

let options = EventsOptionsBuilder::default()
    .since("1h")
    .filters(&filters)
    .build();

docker.events(Some(options));
Source

pub async fn df( &self, options: Option<DataUsageOptions>, ) -> Result<SystemDataUsageResponse, Error>


§Get data usage information

Show docker disk usage

§Returns
§Examples
docker.df(None::<DataUsageOptions>);
Source§

impl Docker

Source

pub async fn list_tasks( &self, options: Option<ListTasksOptions>, ) -> Result<Vec<Task>, Error>


§List Tasks
§Arguments
§Returns
  • A vector of Task struct, wrapped in a Future.
§Examples

use bollard::query_parameters::ListTasksOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("label", vec!["my-task-label"]);

let options = ListTasksOptionsBuilder::default()
    .filters(&filters)
    .build();

docker.list_tasks(Some(options));
Source

pub async fn inspect_task(&self, task_id: &str) -> Result<Task, Error>


§Inspect a Task
§Arguments
  • Task id as a string slice.
§Returns
  • A Models struct, wrapped in a Future.
§Examples

docker.inspect_task("my_task_id");
Source

pub fn task_logs( &self, task_id: &str, options: Option<impl Into<LogsOptions>>, ) -> impl Stream<Item = Result<LogOutput, Error>>


§Get Task Logs

Get stdout and stderr logs from a task.

§Arguments
§Returns
§Examples
use bollard::query_parameters::LogsOptionsBuilder;

let options = LogsOptionsBuilder::default()
    .stdout(true)
    .build();

docker.task_logs("my-task-id", Some(options));
Source§

impl Docker

Source

pub async fn list_volumes( &self, options: Option<impl Into<ListVolumesOptions>>, ) -> Result<VolumeListResponse, Error>


§List volumes
§Arguments
§Returns
  • A [Volume List Response]VolumeListResponse) struct, wrapped in a Future.
§Examples

use bollard::query_parameters::ListVolumesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("dangling", vec!("1"));

let options = ListVolumesOptionsBuilder::default().filters(&filters).build();

docker.list_volumes(Some(options));
Source

pub async fn create_volume( &self, config: impl Into<VolumeCreateRequest>, ) -> Result<Volume, Error>


§Create Volume

Create a new volume.

§Arguments
§Returns
  • A Volume struct, wrapped in a Future.
§Examples

use bollard::models::VolumeCreateRequest;

use std::default::Default;

let config = VolumeCreateRequest {
    name: Some(String::from("certs")),
    ..Default::default()
};

docker.create_volume(config);
Source

pub async fn inspect_volume(&self, volume_name: &str) -> Result<Volume, Error>


§Inspect a Volume
§Arguments
  • Volume name as a string slice.
§Returns
  • A Volume struct, wrapped in a Future.
§Examples

docker.inspect_volume("my_volume_name");
Source

pub async fn remove_volume( &self, volume_name: &str, options: Option<impl Into<RemoveVolumeOptions>>, ) -> Result<(), Error>


§Remove a Volume
§Arguments
  • Volume name as a string slice.
§Arguments
§Returns
  • unit type (), wrapped in a Future.
§Examples

use bollard::query_parameters::RemoveVolumeOptionsBuilder;

let options = RemoveVolumeOptionsBuilder::default().force(true).build();

docker.remove_volume("my_volume_name", Some(options));
Source

pub async fn prune_volumes( &self, options: Option<impl Into<PruneVolumesOptions>>, ) -> Result<VolumePruneResponse, Error>


§Prune Volumes

Delete unused volumes.

§Arguments
§Returns
§Examples

use bollard::query_parameters::PruneVolumesOptionsBuilder;

use std::collections::HashMap;

let mut filters = HashMap::new();
filters.insert("label", vec!["maintainer=some_maintainer"]);

let options = PruneVolumesOptionsBuilder::default().filters(&filters).build();

docker.prune_volumes(Some(options));

Trait Implementations§

Source§

impl Clone for Docker

Source§

fn clone(&self) -> Docker

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Docker

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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