-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtemplate_showcase.rs
More file actions
360 lines (313 loc) · 11.6 KB
/
template_showcase.rs
File metadata and controls
360 lines (313 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//! Comprehensive showcase of Docker template features
//!
//! This example demonstrates advanced template usage patterns including:
//! - Container orchestration with dependencies
//! - Health checking and readiness probes
//! - Data persistence across container restarts
//! - Custom networking between containers
//! - Resource management and limits
//! - Connection string generation
//! - Multi-container application setup
#[cfg(feature = "templates")]
use docker_wrapper::{
DockerCommand, MongodbConnectionString, MongodbTemplate, MysqlConnectionString, MysqlTemplate,
NetworkCreateCommand, NginxTemplate, PostgresConnectionString, PostgresTemplate, RedisTemplate,
Template, VolumeCreateCommand, VolumeRmCommand,
};
#[cfg(feature = "templates")]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🚀 Docker Template Showcase\n");
println!("This example demonstrates a complete microservices setup with:");
println!("- Custom networking for container communication");
println!("- Persistent data volumes");
println!("- Health checks and readiness probes");
println!("- Resource limits");
println!("- Connection management\n");
// Generate unique suffix for all resources to avoid conflicts on re-runs
let unique_id = uuid::Uuid::new_v4();
// Create a custom network for our application
println!("Creating application network...");
let network_name = format!("showcase-network-{}", unique_id);
NetworkCreateCommand::new(&network_name)
.driver("bridge")
.execute()
.await?;
println!(" Network '{}' created", network_name);
// Create named volumes for persistence
println!("\nCreating persistent volumes...");
let postgres_volume = format!("showcase-postgres-{}", unique_id);
let mongo_volume = format!("showcase-mongo-{}", unique_id);
let redis_volume = format!("showcase-redis-{}", unique_id);
// Container names also need unique suffixes to avoid conflicts
let redis_name = format!("showcase-redis-{}", unique_id);
let postgres_name = format!("showcase-postgres-{}", unique_id);
let mysql_name = format!("showcase-mysql-{}", unique_id);
let mongodb_name = format!("showcase-mongodb-{}", unique_id);
let nginx_name = format!("showcase-nginx-{}", unique_id);
VolumeCreateCommand::new()
.name(&postgres_volume)
.execute()
.await?;
VolumeCreateCommand::new()
.name(&mongo_volume)
.execute()
.await?;
VolumeCreateCommand::new()
.name(&redis_volume)
.execute()
.await?;
println!(" Volumes created");
// Deploy Redis as cache layer
println!("\nDeploying Redis cache...");
let redis = RedisTemplate::new(&redis_name)
.port(16379)
.password("redis_secure_pass")
.with_persistence(&redis_volume)
.memory_limit("256m")
.network(&network_name);
let redis_id = redis.start_and_wait().await?;
println!(" Redis ready (Container: {})", &redis_id[..12]);
// Test Redis connection
let ping_result = redis
.exec(vec!["redis-cli", "-a", "redis_secure_pass", "ping"])
.await?;
println!(" Redis PING: {}", ping_result.stdout.trim());
// Deploy PostgreSQL as primary database
println!("\nDeploying PostgreSQL database...");
let postgres = PostgresTemplate::new(&postgres_name)
.port(15432)
.database("showcase_db")
.user("app_user")
.password("postgres_secure_pass")
.with_persistence(&postgres_volume)
.memory_limit("512m")
.network(&network_name)
.postgres_args("--max_connections=100");
let postgres_id = postgres.start_and_wait().await?;
println!(" PostgreSQL ready (Container: {})", &postgres_id[..12]);
// Get PostgreSQL connection details
let pg_conn = PostgresConnectionString::from_template(&postgres);
println!(" 📋 Connection URL: {}", pg_conn.url());
println!(" 📋 Connection String: {}", pg_conn.key_value());
// Create sample schema
println!(" 🔨 Creating sample schema...");
postgres
.exec(vec![
"psql",
"-U",
"app_user",
"-d",
"showcase_db",
"-c",
"CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);",
])
.await?;
postgres
.exec(vec![
"psql",
"-U",
"app_user",
"-d",
"showcase_db",
"-c",
"INSERT INTO users (username, email) VALUES
('alice', '[email protected]'),
('bob', '[email protected]')
ON CONFLICT DO NOTHING;",
])
.await?;
println!(" ✅ Schema created and sample data inserted");
// Deploy MySQL as secondary database
println!("\n🐬 Deploying MySQL database...");
let mysql = MysqlTemplate::new(&mysql_name)
.port(13306)
.database("analytics_db")
.user("analytics_user")
.password("mysql_secure_pass")
.root_password("mysql_root_pass")
.character_set("utf8mb4")
.collation("utf8mb4_unicode_ci")
.memory_limit("512m")
.network(&network_name);
let mysql_id = mysql.start_and_wait().await?;
println!(" ✅ MySQL ready (Container: {})", &mysql_id[..12]);
let mysql_conn = MysqlConnectionString::from_template(&mysql);
println!(" 📋 Connection URL: {}", mysql_conn.url());
println!(" 📋 JDBC URL: {}", mysql_conn.jdbc());
// Deploy MongoDB for document storage
println!("\n🍃 Deploying MongoDB...");
let mongodb = MongodbTemplate::new(&mongodb_name)
.port(27018)
.root_username("mongo_admin")
.root_password("mongo_secure_pass")
.database("documents_db")
.with_auth()
.with_persistence(&mongo_volume)
.memory_limit("512m")
.network(&network_name);
let mongodb_id = mongodb.start_and_wait().await?;
println!(" ✅ MongoDB ready (Container: {})", &mongodb_id[..12]);
let mongo_conn = MongodbConnectionString::from_template(&mongodb);
println!(" 📋 Connection URL: {}", mongo_conn.url());
// Deploy Nginx as reverse proxy
println!("\n🌐 Deploying Nginx reverse proxy...");
// Create a simple HTML page
let html_content = r#"<!DOCTYPE html>
<html>
<head>
<title>Docker Template Showcase</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.service {
background: #f0f0f0;
padding: 15px;
margin: 10px 0;
border-radius: 5px;
}
.status { color: green; font-weight: bold; }
</style>
</head>
<body>
<h1>🚀 Docker Template Showcase</h1>
<p>All services are running successfully!</p>
<div class="service">
<h3>🔴 Redis Cache</h3>
<p class="status">✅ Running on port 16379</p>
</div>
<div class="service">
<h3>🐘 PostgreSQL Database</h3>
<p class="status">✅ Running on port 15432</p>
</div>
<div class="service">
<h3>🐬 MySQL Database</h3>
<p class="status">✅ Running on port 13306</p>
</div>
<div class="service">
<h3>🍃 MongoDB</h3>
<p class="status">✅ Running on port 27018</p>
</div>
</body>
</html>"#;
// Create a temporary file for the HTML content
use std::io::Write;
let temp_dir = std::env::temp_dir();
let html_file = temp_dir.join("showcase-index.html");
let mut file = std::fs::File::create(&html_file)?;
file.write_all(html_content.as_bytes())?;
file.sync_all()?;
let nginx = NginxTemplate::new(&nginx_name)
.port(8080)
.content(html_file.to_str().unwrap())
.memory_limit("128m")
.network(&network_name);
let nginx_id = nginx.start_and_wait().await?;
println!(" ✅ Nginx ready (Container: {})", &nginx_id[..12]);
println!(" 🌐 Access the dashboard at: http://localhost:8080");
// Verify all containers are running
println!("\n✨ Verifying all services...");
let mut all_running = true;
if redis.is_running().await? {
println!(" ✅ Redis is healthy");
} else {
println!(" ❌ Redis is not running");
all_running = false;
}
if postgres.is_running().await? {
println!(" ✅ PostgreSQL is healthy");
} else {
println!(" ❌ PostgreSQL is not running");
all_running = false;
}
if mysql.is_running().await? {
println!(" ✅ MySQL is healthy");
} else {
println!(" ❌ MySQL is not running");
all_running = false;
}
if mongodb.is_running().await? {
println!(" ✅ MongoDB is healthy");
} else {
println!(" ❌ MongoDB is not running");
all_running = false;
}
if nginx.is_running().await? {
println!(" ✅ Nginx is healthy");
} else {
println!(" ❌ Nginx is not running");
all_running = false;
}
if all_running {
println!("\n🎉 All services are running successfully!");
} else {
println!("\n⚠️ Some services failed to start properly");
}
// Demonstrate inter-container communication
println!("\n🔗 Testing inter-container communication...");
// Redis can be accessed from other containers using container name
let redis_ping_cmd = format!(
"apt-get update -qq && apt-get install -qq -y redis-tools > /dev/null 2>&1 && redis-cli -h {} -a redis_secure_pass ping",
redis_name
);
let redis_internal_test = postgres.exec(vec!["sh", "-c", &redis_ping_cmd]).await;
if let Ok(result) = redis_internal_test {
if result.stdout.contains("PONG") {
println!(" ✅ PostgreSQL can connect to Redis via network");
}
}
// Show container logs
println!("\n📜 Sample logs from services:");
let redis_logs = redis.logs(false, Some("5")).await?;
println!("\n Redis logs (last 5 lines):");
for line in redis_logs.stdout.lines().take(5) {
println!(" {}", line);
}
// Interactive prompt
println!("\n💡 Services are running. Press Enter to clean up...");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
// Cleanup
println!("\n🧹 Cleaning up...");
println!(" Stopping containers...");
nginx.stop().await?;
mongodb.stop().await?;
mysql.stop().await?;
postgres.stop().await?;
redis.stop().await?;
println!(" Removing containers...");
nginx.remove().await?;
mongodb.remove().await?;
mysql.remove().await?;
postgres.remove().await?;
redis.remove().await?;
println!(" Removing volumes...");
VolumeRmCommand::new(&redis_volume)
.force()
.execute()
.await?;
VolumeRmCommand::new(&postgres_volume)
.force()
.execute()
.await?;
VolumeRmCommand::new(&mongo_volume)
.force()
.execute()
.await?;
println!(" Removing network...");
use docker_wrapper::NetworkRmCommand;
NetworkRmCommand::new(&network_name).execute().await?;
println!("\n✅ All resources cleaned up successfully!");
println!("👋 Thank you for trying the Docker Template Showcase!");
Ok(())
}
#[cfg(not(feature = "templates"))]
fn main() {
eprintln!("This example requires the 'templates' feature to be enabled.");
eprintln!("Run with: cargo run --features templates --example template_showcase");
}