62 lines
2.1 KiB
Rust
62 lines
2.1 KiB
Rust
// File: /root/code/git.ourworld.tf/herocode/sal/examples/container_example.rs
|
|
|
|
use std::error::Error;
|
|
use sal::virt::nerdctl::Container;
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
// Create a container from an image
|
|
println!("Creating container from image...");
|
|
let container = Container::from_image("my-nginx", "nginx:latest")?
|
|
.with_port("8080:80")
|
|
.with_env("NGINX_HOST", "example.com")
|
|
.with_volume("/tmp/nginx:/usr/share/nginx/html")
|
|
.with_health_check("curl -f http://localhost/ || exit 1")
|
|
.with_detach(true)
|
|
.build()?;
|
|
|
|
println!("Container created successfully");
|
|
|
|
// Execute a command in the container
|
|
println!("Executing command in container...");
|
|
let result = container.exec("echo 'Hello from container'")?;
|
|
println!("Command output: {}", result.stdout);
|
|
|
|
// Get container status
|
|
println!("Getting container status...");
|
|
let status = container.status()?;
|
|
println!("Container status: {}", status.status);
|
|
|
|
// Get resource usage
|
|
println!("Getting resource usage...");
|
|
let resources = container.resources()?;
|
|
println!("CPU usage: {}", resources.cpu_usage);
|
|
println!("Memory usage: {}", resources.memory_usage);
|
|
|
|
// Stop and remove the container
|
|
println!("Stopping and removing container...");
|
|
container.stop()?;
|
|
container.remove()?;
|
|
|
|
println!("Container stopped and removed");
|
|
|
|
// Get a container by name (if it exists)
|
|
println!("\nGetting a container by name...");
|
|
match Container::new("existing-container") {
|
|
Ok(container) => {
|
|
if container.container_id.is_some() {
|
|
println!("Found container with ID: {}", container.container_id.as_ref().unwrap());
|
|
|
|
// Perform operations on the existing container
|
|
let status = container.status()?;
|
|
println!("Container status: {}", status.status);
|
|
} else {
|
|
println!("Container exists but has no ID");
|
|
}
|
|
},
|
|
Err(e) => {
|
|
println!("Error getting container: {}", e);
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
} |