|
1 | 1 | //! Example demonstrating container lifecycle commands including rm, kill, and logs |
2 | 2 |
|
3 | 3 | use docker_wrapper::command::DockerCommand; |
4 | | -use docker_wrapper::{KillCommand, LogsCommand, RmCommand, RunCommand}; |
| 4 | +use docker_wrapper::{KillCommand, LogsCommand, RmCommand, RunCommand, StopCommand}; |
5 | 5 | use std::time::Duration; |
6 | 6 | use tokio::time::sleep; |
7 | 7 |
|
@@ -42,22 +42,51 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { |
42 | 42 | .await?; |
43 | 43 | println!("Recent logs:\n{}", logs.stdout); |
44 | 44 |
|
45 | | - // Send SIGTERM to the container |
46 | | - println!("\nSending SIGTERM to container..."); |
| 45 | + // Send SIGKILL to the container (demonstrates kill command) |
| 46 | + println!("\nSending SIGKILL to container..."); |
47 | 47 | let _kill_result = KillCommand::new(container_name) |
48 | | - .signal("SIGTERM") |
| 48 | + .signal("SIGKILL") |
49 | 49 | .run() |
50 | 50 | .await?; |
51 | | - println!("Container killed with SIGTERM signal"); |
52 | | - |
53 | | - // Wait a moment for the container to stop |
54 | | - sleep(Duration::from_secs(1)).await; |
| 51 | + println!("Container killed with SIGKILL signal"); |
55 | 52 |
|
56 | 53 | // Remove the container |
57 | 54 | println!("\nRemoving container..."); |
58 | 55 | let _rm_result = RmCommand::new(container_name).run().await?; |
59 | 56 | println!("Container removed successfully"); |
60 | 57 |
|
| 58 | + // Demonstrate the proper stop -> rm pattern |
| 59 | + println!("\n--- Demonstrating stop -> rm pattern ---\n"); |
| 60 | + |
| 61 | + // Start another container |
| 62 | + println!("Starting another container..."); |
| 63 | + let run_result = RunCommand::new("alpine:latest") |
| 64 | + .name(container_name) |
| 65 | + .detach() |
| 66 | + .cmd(vec![ |
| 67 | + "sh".to_string(), |
| 68 | + "-c".to_string(), |
| 69 | + "while true; do echo 'Running...'; sleep 1; done".to_string(), |
| 70 | + ]) |
| 71 | + .execute() |
| 72 | + .await?; |
| 73 | + println!("Container started with ID: {}", run_result.0); |
| 74 | + |
| 75 | + sleep(Duration::from_secs(2)).await; |
| 76 | + |
| 77 | + // Stop the container gracefully (sends SIGTERM, waits, then SIGKILL) |
| 78 | + println!("\nStopping container gracefully..."); |
| 79 | + let stop_result = StopCommand::new(container_name) |
| 80 | + .timeout(5) |
| 81 | + .execute() |
| 82 | + .await?; |
| 83 | + println!("Container stopped: {:?}", stop_result.stopped_containers); |
| 84 | + |
| 85 | + // Now remove it (no force needed since it's stopped) |
| 86 | + println!("\nRemoving container..."); |
| 87 | + let _rm_result = RmCommand::new(container_name).run().await?; |
| 88 | + println!("Container removed successfully"); |
| 89 | + |
61 | 90 | println!("\nLifecycle example completed!"); |
62 | 91 | Ok(()) |
63 | 92 | } |
0 commit comments