Expand description
§docker-wrapper
A comprehensive, type-safe Docker CLI wrapper for Rust applications.
docker-wrapper
provides a clean, idiomatic Rust interface to Docker’s command-line interface,
supporting all major Docker commands with strong typing, async/await support, and a consistent
builder pattern API.
§Features
- Complete Docker CLI coverage: Implements all 35 essential Docker commands
- Type-safe builder pattern: Compile-time validation of command construction
- Async/await support: Built on Tokio for efficient async operations
- Streaming support: Real-time output streaming for long-running commands
- Docker Compose support: Optional feature for multi-container orchestration
- Container templates: Pre-configured templates for Redis,
PostgreSQL
,MongoDB
, etc. - Zero dependencies on Docker SDK: Works directly with the Docker CLI
- Comprehensive error handling: Detailed error messages and types
- Well-tested: Extensive unit and integration test coverage
§Quick Start
Add docker-wrapper
to your Cargo.toml
:
[dependencies]
docker-wrapper = "0.2"
tokio = { version = "1", features = ["full"] }
For Docker Compose support, enable the compose
feature:
[dependencies]
docker-wrapper = { version = "0.2", features = ["compose"] }
§Basic Usage
§Running a Container
use docker_wrapper::{DockerCommand, RunCommand};
// Run a simple container
let output = RunCommand::new("nginx:latest")
.name("my-web-server")
.port(8080, 80)
.detach()
.execute()
.await?;
println!("Container started: {}", output.0);
§Building an Image
use docker_wrapper::{DockerCommand, BuildCommand};
let output = BuildCommand::new(".")
.tag("my-app:latest")
.file("Dockerfile")
.build_arg("VERSION", "1.0.0")
.execute()
.await?;
if let Some(image_id) = &output.image_id {
println!("Built image: {}", image_id);
}
§Listing Containers
use docker_wrapper::{DockerCommand, PsCommand};
let output = PsCommand::new()
.all()
.format_json()
.execute()
.await?;
for container in output.containers {
println!("{}: {}", container.names, container.status);
}
§Streaming Output
For long-running commands, use the streaming API to process output in real-time:
use docker_wrapper::{BuildCommand, StreamHandler, StreamableCommand};
// Stream build output to console
let result = BuildCommand::new(".")
.tag("my-app:latest")
.stream(StreamHandler::print())
.await?;
if result.is_success() {
println!("Build completed successfully!");
}
§Container Templates
Use pre-configured templates for common services:
use docker_wrapper::{RedisTemplate, Template};
// Start Redis with persistence and custom configuration
let redis = RedisTemplate::new("my-redis")
.port(6379)
.password("secret")
.memory_limit("256m")
.with_persistence("redis-data")
.custom_image("redis", "7-alpine");
let container_id = redis.start().await?;
println!("Redis started: {}", container_id);
// Clean up
redis.stop().await?;
§Docker Compose Support
When the compose
feature is enabled, you can manage multi-container applications:
use docker_wrapper::compose::{ComposeCommand, ComposeUpCommand, ComposeDownCommand};
// Start services defined in docker-compose.yml
ComposeUpCommand::new()
.file("docker-compose.yml")
.detach()
.execute()
.await?;
// Stop and remove services
ComposeDownCommand::new()
.volumes()
.execute()
.await?;
§Architecture
The crate is organized around several key design patterns:
§Command Trait Pattern
All Docker commands implement the DockerCommand
trait, providing a consistent interface:
new()
- Create a new command instanceexecute()
- Run the command and return typed output- Builder methods for setting options
§Builder Pattern
Commands use the builder pattern for configuration, allowing fluent and intuitive API usage:
RunCommand::new("alpine")
.name("my-container")
.env("KEY", "value")
.volume("/host/path", "/container/path")
.workdir("/app")
.cmd(vec!["echo".to_string(), "hello".to_string()])
.execute()
.await?;
§Error Handling
All operations return Result<T, docker_wrapper::Error>
, providing detailed error information:
match RunCommand::new("invalid:image").execute().await {
Ok(output) => println!("Container ID: {}", output.0),
Err(e) => eprintln!("Failed to run container: {}", e),
}
§Command Coverage
§Container Commands
run
- Run a new containerexec
- Execute commands in running containersps
- List containerscreate
- Create a new container without starting itstart
- Start stopped containersstop
- Stop running containersrestart
- Restart containerskill
- Kill running containersrm
- Remove containerspause
- Pause running containersunpause
- Unpause paused containersattach
- Attach to running containerswait
- Wait for containers to stoplogs
- Fetch container logstop
- Display running processes in containersstats
- Display resource usage statisticsport
- List port mappingsrename
- Rename containersupdate
- Update container configurationcp
- Copy files between containers and hostdiff
- Inspect filesystem changesexport
- Export container filesystemcommit
- Create image from container
§Image Commands
images
- List imagespull
- Pull images from registrypush
- Push images to registrybuild
- Build images from Dockerfileload
- Load images from tar archivesave
- Save images to tar archivermi
- Remove imagestag
- Tag imagesimport
- Import images from tarballhistory
- Show image historyinspect
- Display detailed informationsearch
- Search Docker Hub for images
§System Commands
info
- Display system informationversion
- Show Docker versionevents
- Monitor Docker eventslogin
- Log in to registrylogout
- Log out from registry
§Prerequisites Check
Ensure Docker is installed and accessible:
use docker_wrapper::ensure_docker;
// Check Docker availability and version
let docker_info = ensure_docker().await?;
println!("Docker version: {}.{}.{}",
docker_info.version.major,
docker_info.version.minor,
docker_info.version.patch);
§Best Practices
§Resource Cleanup
Always clean up containers and resources:
// Use auto-remove for temporary containers
RunCommand::new("alpine")
.remove() // Automatically remove when stopped
.execute()
.await?;
// Or manually remove containers
RmCommand::new("my-container")
.force()
.execute()
.await?;
§Error Handling
Handle errors appropriately for production use:
async fn run_container() -> Result<String, Error> {
let output = RunCommand::new("nginx")
.detach()
.execute()
.await?;
Ok(output.0)
}
match run_container().await {
Ok(id) => println!("Started container: {}", id),
Err(Error::CommandFailed { stderr, .. }) => {
eprintln!("Docker command failed: {}", stderr);
}
Err(e) => eprintln!("Unexpected error: {}", e),
}
§Examples
The examples/
directory contains comprehensive examples:
basic_usage.rs
- Common Docker operationscontainer_lifecycle.rs
- Container management patternsdocker_compose.rs
- Docker Compose usagestreaming.rs
- Real-time output streamingerror_handling.rs
- Error handling patterns
Run examples with:
cargo run --example basic_usage
cargo run --example streaming
cargo run --features compose --example docker_compose
§Migration from Docker CLI
Migrating from shell scripts to docker-wrapper
is straightforward:
Shell:
docker run -d --name web -p 8080:80 nginx:latest
Rust:
RunCommand::new("nginx:latest")
.detach()
.name("web")
.port(8080, 80)
.execute()
.await?;
§Contributing
Contributions are welcome! Please see the GitHub repository for contribution guidelines and development setup.
§License
This project is licensed under the MIT License - see the LICENSE file for details.
Re-exports§
pub use stream::OutputLine;
pub use stream::StreamHandler;
pub use stream::StreamResult;
pub use stream::StreamableCommand;
pub use command::attach::AttachCommand;
pub use command::attach::AttachResult;
pub use command::bake::BakeCommand;
pub use command::build::BuildCommand;
pub use command::build::BuildOutput;
pub use command::builder::BuilderBuildCommand;
pub use command::builder::BuilderPruneCommand;
pub use command::builder::BuilderPruneResult;
pub use command::commit::CommitCommand;
pub use command::commit::CommitResult;
pub use command::container_prune::ContainerPruneCommand;
pub use command::container_prune::ContainerPruneResult;
pub use command::context::ContextCreateCommand;
pub use command::context::ContextInfo;
pub use command::context::ContextInspectCommand;
pub use command::context::ContextLsCommand;
pub use command::context::ContextRmCommand;
pub use command::context::ContextUpdateCommand;
pub use command::context::ContextUseCommand;
pub use command::cp::CpCommand;
pub use command::cp::CpResult;
pub use command::create::CreateCommand;
pub use command::create::CreateResult;
pub use command::diff::DiffCommand;
pub use command::diff::DiffResult;
pub use command::diff::FilesystemChange;
pub use command::diff::FilesystemChangeType;
pub use command::events::DockerEvent;
pub use command::events::EventActor;
pub use command::events::EventsCommand;
pub use command::events::EventsResult;
pub use command::exec::ExecCommand;
pub use command::exec::ExecOutput;
pub use command::export::ExportCommand;
pub use command::export::ExportResult;
pub use command::history::HistoryCommand;
pub use command::history::HistoryResult;
pub use command::history::ImageLayer;
pub use command::image_prune::DeletedImage;
pub use command::image_prune::ImagePruneCommand;
pub use command::image_prune::ImagePruneResult;
pub use command::images::ImageInfo;
pub use command::images::ImagesCommand;
pub use command::images::ImagesOutput;
pub use command::import::ImportCommand;
pub use command::import::ImportResult;
pub use command::info::DockerInfo as SystemDockerInfo;
pub use command::info::InfoCommand;
pub use command::info::InfoOutput;
pub use command::info::SystemInfo;
pub use command::init::InitCommand;
pub use command::init::InitOutput;
pub use command::init::InitTemplate;
pub use command::inspect::InspectCommand;
pub use command::inspect::InspectOutput;
pub use command::kill::KillCommand;
pub use command::kill::KillResult;
pub use command::load::LoadCommand;
pub use command::load::LoadResult;
pub use command::login::LoginCommand;
pub use command::login::LoginOutput;
pub use command::logout::LogoutCommand;
pub use command::logout::LogoutOutput;
pub use command::logs::LogsCommand;
pub use command::network::NetworkConnectCommand;
pub use command::network::NetworkConnectResult;
pub use command::network::NetworkCreateCommand;
pub use command::network::NetworkCreateResult;
pub use command::network::NetworkDisconnectCommand;
pub use command::network::NetworkDisconnectResult;
pub use command::network::NetworkInfo;
pub use command::network::NetworkInspectCommand;
pub use command::network::NetworkInspectOutput;
pub use command::network::NetworkLsCommand;
pub use command::network::NetworkLsOutput;
pub use command::network::NetworkPruneCommand;
pub use command::network::NetworkPruneResult;
pub use command::network::NetworkRmCommand;
pub use command::network::NetworkRmResult;
pub use command::pause::PauseCommand;
pub use command::pause::PauseResult;
pub use command::port::PortCommand;
pub use command::port::PortMapping as PortMappingInfo;
pub use command::port::PortResult;
pub use command::ps::ContainerInfo;
pub use command::ps::PsCommand;
pub use command::ps::PsFormat;
pub use command::ps::PsOutput;
pub use command::pull::PullCommand;
pub use command::push::PushCommand;
pub use command::rename::RenameCommand;
pub use command::rename::RenameResult;
pub use command::restart::RestartCommand;
pub use command::restart::RestartResult;
pub use command::rm::RmCommand;
pub use command::rm::RmResult;
pub use command::rmi::RmiCommand;
pub use command::rmi::RmiResult;
pub use command::run::ContainerId;
pub use command::run::MountType;
pub use command::run::RunCommand;
pub use command::run::VolumeMount;
pub use command::save::SaveCommand;
pub use command::save::SaveResult;
pub use command::search::RepositoryInfo;
pub use command::search::SearchCommand;
pub use command::search::SearchOutput;
pub use command::start::StartCommand;
pub use command::start::StartResult;
pub use command::stats::ContainerStats;
pub use command::stats::StatsCommand;
pub use command::stats::StatsResult;
pub use command::stop::StopCommand;
pub use command::stop::StopResult;
pub use command::system::BuildCacheInfo;
pub use command::system::BuildCacheUsage;
pub use command::system::ContainerInfo as SystemContainerInfo;
pub use command::system::ContainerUsage;
pub use command::system::DiskUsage;
pub use command::system::ImageInfo as SystemImageInfo;
pub use command::system::ImageUsage;
pub use command::system::PruneResult;
pub use command::system::SystemDfCommand;
pub use command::system::SystemPruneCommand;
pub use command::system::VolumeInfo as SystemVolumeInfo;
pub use command::system::VolumeUsage;
pub use command::tag::TagCommand;
pub use command::tag::TagResult;
pub use command::top::ContainerProcess;
pub use command::top::TopCommand;
pub use command::top::TopResult;
pub use command::unpause::UnpauseCommand;
pub use command::unpause::UnpauseResult;
pub use command::update::UpdateCommand;
pub use command::update::UpdateResult;
pub use command::version::ClientVersion;
pub use command::version::ServerVersion;
pub use command::version::VersionCommand;
pub use command::version::VersionInfo;
pub use command::version::VersionOutput;
pub use command::volume::VolumeCreateCommand;
pub use command::volume::VolumeCreateResult;
pub use command::volume::VolumeInfo;
pub use command::volume::VolumeInspectCommand;
pub use command::volume::VolumeInspectOutput;
pub use command::volume::VolumeLsCommand;
pub use command::volume::VolumeLsOutput;
pub use command::volume::VolumePruneCommand;
pub use command::volume::VolumePruneResult;
pub use command::volume::VolumeRmCommand;
pub use command::volume::VolumeRmResult;
pub use command::wait::WaitCommand;
pub use command::wait::WaitResult;
pub use command::CommandExecutor;
pub use command::CommandOutput;
pub use command::DockerCommand;
pub use command::EnvironmentBuilder;
pub use command::PortBuilder;
pub use command::PortMapping;
pub use command::Protocol;
pub use debug::BackoffStrategy;
pub use debug::DebugConfig;
pub use debug::DebugExecutor;
pub use debug::DryRunPreview;
pub use debug::RetryPolicy;
pub use error::Error;
pub use error::Result;
pub use platform::Platform;
pub use platform::PlatformInfo;
pub use platform::Runtime;
pub use prerequisites::ensure_docker;
pub use prerequisites::DockerInfo;
pub use prerequisites::DockerPrerequisites;
pub use template::Template;
pub use template::TemplateBuilder;
pub use template::TemplateConfig;
pub use template::TemplateError;
pub use template::redis::RedisInsightTemplate;
pub use template::redis::RedisTemplate;
pub use template::redis::RedisSentinelTemplate;
pub use template::redis::SentinelConnectionInfo;
pub use template::redis::SentinelInfo;
pub use template::redis::ClusterInfo;
pub use template::redis::NodeInfo;
pub use template::redis::NodeRole;
pub use template::redis::RedisClusterConnection;
pub use template::redis::RedisClusterTemplate;
pub use template::redis::RedisEnterpriseConnectionInfo;
pub use template::redis::RedisEnterpriseTemplate;
pub use template::database::PostgresConnectionString;
pub use template::database::PostgresTemplate;
pub use template::database::MysqlConnectionString;
pub use template::database::MysqlTemplate;
pub use template::database::MongodbConnectionString;
pub use template::database::MongodbTemplate;
pub use template::web::NginxTemplate;
Modules§
- command
- Command trait architecture for extensible Docker command implementations.
- compose
- Docker Compose command implementations.
- debug
- Debugging and reliability features for Docker commands.
- error
- Error types for the docker-wrapper crate.
- platform
- Platform detection and runtime abstraction for Docker environments.
- prerequisites
- Prerequisites module for Docker detection and validation.
- stream
- Streaming support for Docker command output.
- template
- Container templates module
Constants§
- VERSION
- The version of this crate