The main interface for calling the Docker API. Construct a new Docker instance using one of the connect methods:
Docker::connect_with_http_defaults
Docker::connect_with_named_pipe_defaults
Docker::connect_with_ssl_defaults
Docker::connect_with_unix_defaults
Docker::connect_with_local_defaults
Returns a list of containers.
use bollard::container::ListContainersOptions;
use std::collections::HashMap;
use std::default::Default;
let mut filters = HashMap::new();
filters.insert("health", vec!["unhealthy"]);
let options = Some(ListContainersOptions{
all: true,
filters,
..Default::default()
});
docker.list_containers(options);
Prepares a container for a subsequent start operation.
use bollard::container::{CreateContainerOptions, Config};
use std::default::Default;
let options = Some(CreateContainerOptions{
name: "my-new-container",
platform: None,
});
let config = Config {
image: Some("hello-world"),
cmd: Some(vec!["/hello"]),
..Default::default()
};
docker.create_container(options, config);
Starts a container, after preparing it with the Create Container API.
()
, wrapped in a Future.use bollard::container::StartContainerOptions;
docker.start_container("hello-world", None::<StartContainerOptions<String>>);
Stops a container.
()
, wrapped in a Future.use bollard::container::StopContainerOptions;
let options = Some(StopContainerOptions{
t: 30,
});
docker.stop_container("hello-world", options);
Remove a container.
()
, wrapped in a Future.
use bollard::container::RemoveContainerOptions;
use std::default::Default;
let options = Some(RemoveContainerOptions{
force: true,
..Default::default()
});
docker.remove_container("hello-world", options);
Wait for a container to stop. This is a non-blocking operation, the resulting stream will end when the container stops.
use bollard::container::WaitContainerOptions;
let options = Some(WaitContainerOptions{
condition: "not-running",
});
docker.wait_container("hello-world", options);
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.
use bollard::container::AttachContainerOptions;
let options = Some(AttachContainerOptions::<String>{
stdin: Some(true),
stdout: Some(true),
stderr: Some(true),
stream: Some(true),
logs: Some(true),
detach_keys: Some("ctrl-c".to_string()),
});
docker.attach_container("hello-world", options);
Resize the container’s TTY.
use bollard::container::ResizeContainerTtyOptions;
let options = ResizeContainerTtyOptions {
width: 50,
height: 20,
};
docker.resize_container_tty("hello-world", options);
Restart a container.
()
, wrapped in a Future.
use bollard::container::RestartContainerOptions;
let options = Some(RestartContainerOptions{
t: 30,
});
docker.restart_container("postgres", options);
Inspect a container.
use bollard::container::InspectContainerOptions;
let options = Some(InspectContainerOptions{
size: false,
});
docker.inspect_container("hello-world", options);
List processes running inside a container.
use bollard::container::TopOptions;
let options = Some(TopOptions{
ps_args: "aux",
});
docker.top_processes("fussybeaver/uhttpd", options);
Get container logs.
use bollard::container::LogsOptions;
use std::default::Default;
let options = Some(LogsOptions::<String>{
stdout: true,
..Default::default()
});
docker.logs("hello-world", options);
Get changes on a container’s filesystem.
docker.container_changes("hello-world");
Get container stats based on resource usage.
use bollard::container::StatsOptions;
let options = Some(StatsOptions{
stream: false,
one_shot: true,
});
docker.stats("hello-world", options);
Kill a container.
()
, wrapped in a Future.
use bollard::container::KillContainerOptions;
let options = Some(KillContainerOptions{
signal: "SIGINT",
});
docker.kill_container("postgres", options);
Update a container.
()
, wrapped in a Future.
use bollard::container::UpdateContainerOptions;
use std::default::Default;
let config = UpdateContainerOptions::<String> {
memory: Some(314572800),
memory_swap: Some(314572800),
..Default::default()
};
docker.update_container("postgres", config);
Rename a container.
()
, wrapped in a Future.
use bollard::container::RenameContainerOptions;
let required = RenameContainerOptions {
name: "my_new_container_name"
};
docker.rename_container("hello-world", required);
Delete stopped containers.
use bollard::container::PruneContainersOptions;
use std::collections::HashMap;
let mut filters = HashMap::new();
filters.insert("until", vec!["10m"]);
let options = Some(PruneContainersOptions{
filters
});
docker.prune_containers(options);
Upload a tar archive to be extracted to a path in the filesystem of container id.
()
, wrapped in a Future.use bollard::container::UploadToContainerOptions;
use std::default::Default;
use std::fs::File;
use std::io::Read;
let options = Some(UploadToContainerOptions{
path: "/opt",
..Default::default()
});
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", options, contents.into());
Get a tar archive of a resource in the filesystem of container id.
use bollard::container::DownloadFromContainerOptions;
let options = Some(DownloadFromContainerOptions{
path: "/opt",
});
docker.download_from_container("my-container", options);
A Docker implementation typed to connect to an unsecure Http connection.
Connect using unsecured HTTP using defaults that are signalled by environment variables.
DOCKER_HOST
environment variable, and defaults
to localhost:2375
.use bollard::Docker;
use futures_util::future::TryFutureExt;
let connection = Docker::connect_with_http_defaults().unwrap();
connection.ping()
.map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Connect using unsecured HTTP.
addr
: connection url including scheme and port.timeout
: the read/write timeout (seconds) to use for every hyper connectionclient_version
: the client version to communicate with the server.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!")));
Connect using to either a Unix socket or a Windows named pipe using defaults common to the standard docker configuration.
/var/run/docker.sock
. The windows named pipe
location defaults to //./pipe/docker_engine
.use bollard::Docker;
use futures_util::future::TryFutureExt;
let connection = Docker::connect_with_socket_defaults().unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Connect using a Unix socket or a Windows named pipe.
path
: connection unix socket path or windows named pipe path.timeout
: the read/write timeout (seconds) to use for every hyper connectionclient_version
: the client version to communicate with the server.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!")));
A Docker implementation typed to connect to a Unix socket.
Connect using a Unix socket using defaults common to the standard docker configuration.
DEFAULT_SOCKET
env if its set and the URL
has unix
scheme; otherwise /var/run/docker.sock
.use bollard::Docker;
use futures_util::future::TryFutureExt;
let connection = Docker::connect_with_unix_defaults().unwrap();
connection.ping().map_ok(|_| Ok::<_, ()>(println!("Connected!")));
Connect using a Unix socket.
addr
: connection socket path.timeout
: the read/write timeout (seconds) to use for every hyper connectionclient_version
: the client version to communicate with the server.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!")));
A Docker implementation that wraps away which local implementation we are calling.
Connect using the local machine connection method with default arguments.
This is a simple wrapper over the OS specific handlers:
Connect using the local machine connection method with supplied arguments.
This is a simple wrapper over the OS specific handlers:
Docker::connect_with_unix
Docker::connect_with_named_pipe
Set the request timeout.
This timeout is shared by all requests to the Docker Engine API.
By default, 2 minutes.
Get the current timeout.
This timeout is shared by all requests to the Docker Engine API.
Set the request timeout.
This timeout is shared by all requests to the Docker Engine API.
By default, 2 minutes.
Return the currently set client version.
Check with the server for a supported version, and downgrade the client version if appropriate.
use bollard::Docker;
let docker = Docker::connect_with_http_defaults().unwrap();
async move {
&docker.negotiate_version().await.unwrap().version();
};
Run a command inside a running container.
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);
Starts a previously set up exec instance. If detach is true, this endpoint returns immediately after starting the command.
async {
let message = docker.create_exec("hello-world", config).await.unwrap();
use bollard::exec::StartExecOptions;
docker.start_exec(&message.id, None::<StartExecOptions>);
};
Return low-level information about an exec instance.
async {
let message = docker.create_exec("hello-world", config).await.unwrap();
docker.inspect_exec(&message.id);
};
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.
async {
let message = docker.create_exec("hello-world", config).await.unwrap();
docker.resize_exec(&message.id, ResizeExecOptions {
width: 80,
height: 60
});
};
Returns a list of images on the server. Note that it uses a different, smaller representation of an image than inspecting a single image
use bollard::image::ListImagesOptions;
use std::collections::HashMap;
use std::default::Default;
let mut filters = HashMap::new();
filters.insert("dangling", vec!["true"]);
let options = Some(ListImagesOptions{
all: true,
filters,
..Default::default()
});
docker.list_images(options);
Create an image by either pulling it from a registry or importing it.
from_src
option must be “-”.use bollard::image::CreateImageOptions;
use std::default::Default;
let options = Some(CreateImageOptions{
from_image: "hello-world",
..Default::default()
});
docker.create_image(options, None, None);
// do some other work while the image is pulled from the docker hub...
Return low-level information about an image.
use std::default::Default;
docker.inspect_image("hello-world");
Delete unused images.
use bollard::image::PruneImagesOptions;
use std::collections::HashMap;
let mut filters = HashMap::new();
filters.insert("until", vec!["10m"]);
let options = Some(PruneImagesOptions {
filters
});
docker.prune_images(options);
Return parent layers of an image.
docker.image_history("hello-world");
Search for an image on Docker Hub.
use bollard::image::SearchImagesOptions;
use std::default::Default;
use std::collections::HashMap;
let mut filters = HashMap::new();
filters.insert("until", vec!["10m"]);
let search_options = SearchImagesOptions {
term: "hello-world",
filters,
..Default::default()
};
docker.search_images(search_options);
Remove an image, along with any untagged parent images that were referenced by that image.
use bollard::image::RemoveImageOptions;
use std::default::Default;
let remove_options = Some(RemoveImageOptions {
force: true,
..Default::default()
});
docker.remove_image("hello-world", remove_options, None);
Tag an image so that it becomes part of a repository.
()
, wrapped in a Future.
use bollard::image::TagImageOptions;
use std::default::Default;
let tag_options = Some(TagImageOptions {
tag: "v1.0.1",
..Default::default()
});
docker.tag_image("hello-world", tag_options);
Push an image to a registry.
()
, wrapped in a Future.
use bollard::auth::DockerCredentials;
use bollard::image::PushImageOptions;
use std::default::Default;
let push_options = Some(PushImageOptions {
tag: "v1.0.1",
});
let credentials = Some(DockerCredentials {
username: Some("Jack".to_string()),
password: Some("myverysecretpassword".to_string()),
..Default::default()
});
docker.push_image("hello-world", push_options, credentials);
Create a new image from a container.
use bollard::image::CommitContainerOptions;
use bollard::container::Config;
use std::default::Default;
let options = CommitContainerOptions{
container: "my-running-container",
pause: true,
..Default::default()
};
let config = Config::<String> {
..Default::default()
};
docker.commit_container(options, config);
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.
use bollard::image::BuildImageOptions;
use bollard::container::Config;
use std::default::Default;
use std::fs::File;
use std::io::Read;
let options = BuildImageOptions{
dockerfile: "Dockerfile",
t: "my-image",
rm: true,
..Default::default()
};
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(contents.into()));
Get a tarball containing all images and metadata for a repository.
The root of the resulting tar file will contain the file “mainifest.json”. If the export is
of an image repository, rather than a signle 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.
image_name
string can refer to an individual image and tag (e.g. alpine:latest),
an individual image by ILoad a set of images and tags into a repository.
For details on the format, see the export image endpoint.
use bollard::image::ImportImageOptions;
use bollard::errors::Error;
use std::default::Default;
use futures_util::stream::StreamExt;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tokio_util::codec;
let options = ImportImageOptions{
..Default::default()
};
async move {
let mut file = File::open("tarball.tar.gz").await.unwrap();
let byte_stream = codec::FramedRead::new(file, codec::BytesCodec::new()).map(|r| {
let bytes = r.unwrap().freeze();
Ok::<_, Error>(bytes)
});
let body = hyper::Body::wrap_stream(byte_stream);
let mut stream = docker
.import_image(
ImportImageOptions {
..Default::default()
},
body,
None,
);
while let Some(response) = stream.next().await {
// ...
}
};
Create a new network.
use bollard::network::CreateNetworkOptions;
use std::default::Default;
let config = CreateNetworkOptions {
name: "certs",
..Default::default()
};
docker.create_network(config);
use bollard::network::InspectNetworkOptions;
use std::default::Default;
let config = InspectNetworkOptions {
verbose: true,
scope: "global"
};
docker.inspect_network("my_network_name", Some(config));
use bollard::network::ListNetworksOptions;
use std::collections::HashMap;
let mut list_networks_filters = HashMap::new();
list_networks_filters.insert("label", vec!["maintainer=some_maintainer"]);
let config = ListNetworksOptions {
filters: list_networks_filters,
};
docker.list_networks(Some(config));
()
, wrapped in a Future.
use bollard::network::ConnectNetworkOptions;
use bollard::models::{EndpointSettings, EndpointIpamConfig};
use std::default::Default;
let config = ConnectNetworkOptions {
container: "3613f73ba0e4",
endpoint_config: 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);
()
, wrapped in a Future.
use bollard::network::DisconnectNetworkOptions;
use std::default::Default;
let config = DisconnectNetworkOptions {
container: "3613f73ba0e4",
force: true
};
docker.disconnect_network("my_network_name", config);
Deletes networks which are unused.
use bollard::network::PruneNetworksOptions;
use std::collections::HashMap;
let mut filters = HashMap::new();
filters.insert("label", vec!["maintainer=some_maintainer"]);
let options = PruneNetworksOptions {
filters,
};
docker.prune_networks(Some(options));
Returns a list of secrets.
use bollard::secret::ListSecretsOptions;
use std::collections::HashMap;
use std::default::Default;
let mut filters = HashMap::new();
filters.insert("label", vec!["secret-label=label-value"]);
let options = Some(ListSecretsOptions{
filters,
..Default::default()
});
docker.list_secrets(options);
Create new secret on the docker swarm.
use bollard::secret::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);
Update an existing secret, fails when more than one service use that secret or trying update data.
()
, wrapped in a Future.
use std::collections::HashMap;
use bollard::secret::UpdateSecretOptions;
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 = UpdateSecretOptions { version };
docker.update_secret("my-secret", spec, options).await
};
Returns a list of services.
use bollard::service::ListServicesOptions;
use std::collections::HashMap;
use std::default::Default;
let mut filters = HashMap::new();
filters.insert("mode", vec!["global"]);
let options = Some(ListServicesOptions{
filters,
..Default::default()
});
docker.list_services(options);
Dispatch a new service on the docker swarm
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);
Inspect a service.
use bollard::service::InspectServiceOptions;
let options = Some(InspectServiceOptions{
insert_defaults: true,
});
docker.inspect_service("my-service", options);
Update an existing service
use bollard::service::{
InspectServiceOptions,
ServiceSpec,
ServiceSpecMode,
ServiceSpecModeReplicated,
TaskSpec,
TaskSpecContainerSpec,
UpdateServiceOptions,
};
use std::collections::HashMap;
use std::default::Default;
let result = async move {
let service_name = "my-service";
let current_version = docker.inspect_service(
service_name,
None::<InspectServiceOptions>
).await?.version.unwrap().index.unwrap();
let service = ServiceSpec {
mode: Some(ServiceSpecMode {
replicated: Some(ServiceSpecModeReplicated {
replicas: Some(0)
}),
..Default::default()
}),
..Default::default()
};
let options = UpdateServiceOptions {
version: current_version,
..Default::default()
};
let credentials = None;
docker.update_service("my-service", service, options, credentials).await
};
Stream real-time events from the server.
use bollard::system::EventsOptions;
use time::{Duration, OffsetDateTime};
use std::collections::HashMap;
docker.events(Some(EventsOptions::<String> {
since: Some(OffsetDateTime::now_utc() - Duration::minutes(20)),
until: Some(OffsetDateTime::now_utc()),
filters: HashMap::new(),
}));
Show docker disk usage
docker.df();
use bollard::volume::ListVolumesOptions;
use std::collections::HashMap;
let mut filters = HashMap::new();
filters.insert("dangling", vec!("1"));
let options = ListVolumesOptions {
filters,
};
docker.list_volumes(Some(options));
Create a new volume.
use bollard::volume::CreateVolumeOptions;
use std::default::Default;
let config = CreateVolumeOptions {
name: "certs",
..Default::default()
};
docker.create_volume(config);
()
, wrapped in a Future.
use bollard::volume::RemoveVolumeOptions;
let options = RemoveVolumeOptions {
force: true,
};
docker.remove_volume("my_volume_name", Some(options));
Delete unused volumes.
use bollard::volume::PruneVolumesOptions;
use std::collections::HashMap;
let mut filters = HashMap::new();
filters.insert("label", vec!["maintainer=some_maintainer"]);
let options = PruneVolumesOptions {
filters,
};
docker.prune_volumes(Some(options));
clone_to_uninit
)