0
# JDBC Container Management
1
2
Core container functionality for creating and managing MariaDB instances with JDBC connectivity. Provides database connection details, lifecycle management, and MariaDB-specific configuration options.
3
4
## Capabilities
5
6
### MariaDB Container Creation
7
8
Creates a new MariaDB container instance with specified Docker image.
9
10
```java { .api }
11
/**
12
* Creates MariaDB container with default image (deprecated)
13
* @deprecated Use MariaDBContainer(DockerImageName) instead
14
*/
15
@Deprecated
16
public MariaDBContainer();
17
18
/**
19
* Creates MariaDB container with specified image name
20
* @param dockerImageName Docker image name as string (e.g., "mariadb:10.3.39")
21
*/
22
public MariaDBContainer(String dockerImageName);
23
24
/**
25
* Creates MariaDB container with DockerImageName object
26
* @param dockerImageName DockerImageName with version compatibility validation
27
*/
28
public MariaDBContainer(DockerImageName dockerImageName);
29
```
30
31
**Usage Examples:**
32
33
```java
34
import org.testcontainers.containers.MariaDBContainer;
35
import org.testcontainers.utility.DockerImageName;
36
37
// Recommended approach with DockerImageName
38
MariaDBContainer<?> mariadb = new MariaDBContainer<>(
39
DockerImageName.parse("mariadb:10.3.39")
40
);
41
42
// Alternative with string image name
43
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:11.2.4");
44
45
// Start the container
46
mariadb.start();
47
```
48
49
### Database Connection Information
50
51
Retrieves connection details and JDBC configuration for the running container.
52
53
```java { .api }
54
/**
55
* Returns JDBC connection URL for the MariaDB container
56
* @return JDBC URL with host, port, database name, and URL parameters
57
*/
58
public String getJdbcUrl();
59
60
/**
61
* Returns the MariaDB JDBC driver class name
62
* @return "org.mariadb.jdbc.Driver"
63
*/
64
public String getDriverClassName();
65
66
/**
67
* Returns the configured database name
68
* @return Database name (default: "test")
69
*/
70
public String getDatabaseName();
71
72
/**
73
* Returns the configured database username
74
* @return Username (default: "test")
75
*/
76
public String getUsername();
77
78
/**
79
* Returns the configured database password
80
* @return Password (default: "test")
81
*/
82
public String getPassword();
83
84
/**
85
* Returns the test query string for connection validation
86
* @return "SELECT 1"
87
*/
88
public String getTestQueryString();
89
```
90
91
**Usage Examples:**
92
93
```java
94
try (MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")) {
95
mariadb.start();
96
97
// Get connection information
98
String url = mariadb.getJdbcUrl();
99
String user = mariadb.getUsername();
100
String pass = mariadb.getPassword();
101
String driver = mariadb.getDriverClassName();
102
103
// Use with DriverManager
104
Connection conn = DriverManager.getConnection(url, user, pass);
105
106
// Or with DataSource configuration
107
HikariConfig config = new HikariConfig();
108
config.setJdbcUrl(url);
109
config.setUsername(user);
110
config.setPassword(pass);
111
config.setDriverClassName(driver);
112
}
113
```
114
115
### Container Configuration
116
117
Configures database name, credentials, and MariaDB-specific settings.
118
119
```java { .api }
120
/**
121
* Sets the database name to create in the container
122
* @param databaseName Name of database to create
123
* @return Container instance for method chaining
124
*/
125
public SELF withDatabaseName(String databaseName);
126
127
/**
128
* Sets the database username
129
* @param username Database username (cannot be empty if not "root")
130
* @return Container instance for method chaining
131
*/
132
public SELF withUsername(String username);
133
134
/**
135
* Sets the database password
136
* @param password Database password (can be empty only for root user)
137
* @return Container instance for method chaining
138
*/
139
public SELF withPassword(String password);
140
141
/**
142
* Sets custom MariaDB configuration override directory
143
* @param configPath Path to directory containing MariaDB configuration files
144
* @return Container instance for method chaining
145
*/
146
public SELF withConfigurationOverride(String configPath);
147
```
148
149
**Usage Examples:**
150
151
```java
152
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
153
.withDatabaseName("myapp")
154
.withUsername("appuser")
155
.withPassword("secretpass")
156
.withConfigurationOverride("path/to/mariadb-config");
157
158
// Root user with empty password (allowed)
159
MariaDBContainer<?> rootContainer = new MariaDBContainer<>("mariadb:11.2.4")
160
.withUsername("root"); // Empty password automatically allowed for root
161
162
// Custom JDBC URL parameters
163
MariaDBContainer<?> customContainer = new MariaDBContainer<>("mariadb:10.3.39")
164
.withUrlParam("connectTimeout", "40000")
165
.withUrlParam("rewriteBatchedStatements", "true");
166
```
167
168
### Lifecycle Management
169
170
Container startup, health checks, resource management, and operational commands.
171
172
```java { .api }
173
/**
174
* Returns port numbers used for container liveness checks
175
* @return Set containing MariaDB port (3306)
176
*/
177
public Set<Integer> getLivenessCheckPortNumbers();
178
179
/**
180
* Starts the container (inherited from GenericContainer)
181
*/
182
public void start();
183
184
/**
185
* Stops the container (inherited from GenericContainer)
186
*/
187
public void stop();
188
189
/**
190
* Checks if the container is currently running
191
* @return true if container is running
192
*/
193
public boolean isRunning();
194
195
/**
196
* Gets the host that can be used to connect to the container
197
* @return Host address for container access
198
*/
199
public String getHost();
200
201
/**
202
* Gets the mapped host port for a container port
203
* @param originalPort Container port number
204
* @return Mapped host port number
205
*/
206
public Integer getMappedPort(int originalPort);
207
208
/**
209
* Returns container ID if container is running
210
* @return Container ID string
211
*/
212
public String getContainerId();
213
```
214
215
**Usage Examples:**
216
217
```java
218
// JUnit 5 integration
219
@Testcontainers
220
class MariaDBIntegrationTest {
221
222
@Container
223
static MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
224
.withDatabaseName("testdb")
225
.withUsername("testuser")
226
.withPassword("testpass");
227
228
@Test
229
void testDatabaseConnection() throws SQLException {
230
// Container automatically started by JUnit
231
String jdbcUrl = mariadb.getJdbcUrl();
232
233
try (Connection conn = DriverManager.getConnection(
234
jdbcUrl, mariadb.getUsername(), mariadb.getPassword())) {
235
236
Statement stmt = conn.createStatement();
237
ResultSet rs = stmt.executeQuery("SELECT 1");
238
assertTrue(rs.next());
239
assertEquals(1, rs.getInt(1));
240
}
241
}
242
}
243
244
// Manual lifecycle management
245
try (MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")) {
246
mariadb.start();
247
248
// Container is running, perform tests
249
performDatabaseTests(mariadb);
250
251
// Container automatically stopped when exiting try-with-resources
252
}
253
```
254
255
### Container Execution and File Operations
256
257
Execute commands within the container and manage files for database maintenance and debugging.
258
259
```java { .api }
260
/**
261
* Executes command inside the running container
262
* @param command Command and arguments to execute
263
* @return ExecResult containing exit code, stdout, and stderr
264
*/
265
public Container.ExecResult execInContainer(String... command) throws IOException, InterruptedException;
266
267
/**
268
* Executes command with specific output charset
269
* @param outputCharset Character encoding for command output
270
* @param command Command and arguments to execute
271
* @return ExecResult with decoded output
272
*/
273
public Container.ExecResult execInContainer(Charset outputCharset, String... command) throws IOException, InterruptedException;
274
275
/**
276
* Copies file from host to container
277
* @param mountableFile File to copy (from classpath or filesystem)
278
* @param containerPath Destination path in container
279
*/
280
public void copyFileToContainer(MountableFile mountableFile, String containerPath);
281
282
/**
283
* Copies file from container to host
284
* @param containerPath Source path in container
285
* @param destinationPath Destination path on host
286
*/
287
public void copyFileFromContainer(String containerPath, String destinationPath) throws IOException, InterruptedException;
288
289
/**
290
* Gets container logs
291
* @return Complete container log output
292
*/
293
public String getLogs();
294
295
/**
296
* Gets filtered container logs
297
* @param types Output types to include (STDOUT, STDERR)
298
* @return Filtered log output
299
*/
300
public String getLogs(OutputFrame.OutputType... types);
301
```
302
303
**Usage Examples:**
304
305
```java
306
try (MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")) {
307
mariadb.start();
308
309
// Execute SQL command directly via MySQL CLI
310
Container.ExecResult result = mariadb.execInContainer(
311
"mysql", "-u", mariadb.getUsername(), "-p" + mariadb.getPassword(),
312
"-e", "SHOW DATABASES;"
313
);
314
System.out.println("Databases: " + result.getStdout());
315
316
// Copy backup file to container
317
MountableFile backupFile = MountableFile.forClasspathResource("backup.sql");
318
mariadb.copyFileToContainer(backupFile, "/tmp/backup.sql");
319
320
// Restore from backup
321
Container.ExecResult restoreResult = mariadb.execInContainer(
322
"mysql", "-u", mariadb.getUsername(), "-p" + mariadb.getPassword(),
323
mariadb.getDatabaseName(), "-e", "source /tmp/backup.sql"
324
);
325
326
// Export database dump
327
Container.ExecResult dumpResult = mariadb.execInContainer(
328
"mysqldump", "-u", mariadb.getUsername(), "-p" + mariadb.getPassword(),
329
mariadb.getDatabaseName()
330
);
331
332
// Copy dump to host
333
try (FileWriter writer = new FileWriter("database-dump.sql")) {
334
writer.write(dumpResult.getStdout());
335
}
336
337
// Get container logs for debugging
338
String logs = mariadb.getLogs();
339
System.out.println("Container logs: " + logs);
340
}
341
```
342
343
### Database Initialization
344
345
Sets up database schema and data when the container starts, supporting SQL scripts and programmatic initialization.
346
347
```java { .api }
348
/**
349
* Sets a single initialization script to run on container startup
350
* @param initScriptPath Path to SQL script file (classpath or file system)
351
* @return Container instance for method chaining
352
*/
353
public SELF withInitScript(String initScriptPath);
354
355
/**
356
* Sets multiple initialization scripts to run in order on container startup
357
* @param initScriptPaths Paths to SQL script files
358
* @return Container instance for method chaining
359
*/
360
public SELF withInitScripts(String... initScriptPaths);
361
362
/**
363
* Sets multiple initialization scripts from a collection
364
* @param initScriptPaths Collection of script paths
365
* @return Container instance for method chaining
366
*/
367
public SELF withInitScripts(Iterable<String> initScriptPaths);
368
```
369
370
**Usage Examples:**
371
372
```java
373
// Single initialization script
374
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
375
.withDatabaseName("myapp")
376
.withInitScript("schema.sql");
377
378
// Multiple initialization scripts (executed in order)
379
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
380
.withInitScripts("schema.sql", "data.sql", "indexes.sql");
381
382
// Scripts from classpath
383
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
384
.withInitScript("classpath:db/migration/V1__create_tables.sql");
385
386
mariadb.start();
387
388
// Verify initialization worked
389
try (Connection conn = DriverManager.getConnection(
390
mariadb.getJdbcUrl(), mariadb.getUsername(), mariadb.getPassword())) {
391
392
Statement stmt = conn.createStatement();
393
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM users");
394
rs.next();
395
int userCount = rs.getInt(1);
396
System.out.println("Initialized with " + userCount + " users");
397
}
398
```
399
400
### Timeout Configuration
401
402
Configures container startup and database connection timeouts for reliable operation.
403
404
```java { .api }
405
/**
406
* Sets container startup timeout in seconds
407
* @param startupTimeoutSeconds Maximum time to wait for container startup
408
* @return Container instance for method chaining
409
*/
410
public SELF withStartupTimeoutSeconds(int startupTimeoutSeconds);
411
412
/**
413
* Sets database connection timeout in seconds
414
* @param connectTimeoutSeconds Maximum time to wait for database connection
415
* @return Container instance for method chaining
416
*/
417
public SELF withConnectTimeoutSeconds(int connectTimeoutSeconds);
418
```
419
420
**Usage Examples:**
421
422
```java
423
// Increase timeouts for slow environments
424
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
425
.withStartupTimeoutSeconds(300) // 5 minutes for container startup
426
.withConnectTimeoutSeconds(60); // 1 minute for database connection
427
428
// Critical for CI/CD environments with resource constraints
429
MariaDBContainer<?> ciMariadb = new MariaDBContainer<>("mariadb:10.3.39")
430
.withStartupTimeoutSeconds(600)
431
.withConnectTimeoutSeconds(120);
432
433
ciMariadb.start();
434
```
435
436
### Command Override
437
438
Overrides the default MariaDB startup command for custom server configuration.
439
440
```java { .api }
441
/**
442
* Overrides the container command (inherited from GenericContainer)
443
* @param command Command arguments to pass to MariaDB server
444
* @return Container instance for method chaining
445
*/
446
public SELF withCommand(String... command);
447
```
448
449
**Usage Examples:**
450
451
```java
452
// Override MariaDB server settings via command line
453
MariaDBContainer<?> customMariaDB = new MariaDBContainer<>("mariadb:10.3.39")
454
.withCommand("mysqld --auto_increment_increment=10 --max_connections=200");
455
456
customMariaDB.start();
457
458
// Verify the custom configuration
459
try (Connection conn = DriverManager.getConnection(
460
customMariaDB.getJdbcUrl(),
461
customMariaDB.getUsername(),
462
customMariaDB.getPassword())) {
463
464
Statement stmt = conn.createStatement();
465
ResultSet rs = stmt.executeQuery("SHOW VARIABLES LIKE 'auto_increment_increment'");
466
rs.next();
467
assertEquals("10", rs.getString("Value"));
468
}
469
```
470
471
## Environment Variables
472
473
The MariaDB container automatically configures these environment variables:
474
475
```java { .api }
476
// Automatically set based on configuration
477
private static final String MYSQL_DATABASE = "MYSQL_DATABASE"; // Database name
478
private static final String MYSQL_USER = "MYSQL_USER"; // Username (if not root)
479
private static final String MYSQL_PASSWORD = "MYSQL_PASSWORD"; // User password
480
private static final String MYSQL_ROOT_PASSWORD = "MYSQL_ROOT_PASSWORD"; // Root password
481
private static final String MYSQL_ALLOW_EMPTY_PASSWORD = "MYSQL_ALLOW_EMPTY_PASSWORD"; // Empty password for root
482
```
483
484
## Configuration Files
485
486
Custom MariaDB configuration can be provided through volume mounting:
487
488
```java { .api }
489
// Configuration parameter for custom config directory
490
private static final String MY_CNF_CONFIG_OVERRIDE_PARAM_NAME = "TC_MY_CNF";
491
492
// Configuration mounted to container at:
493
// /etc/mysql/conf.d (MariaDB configuration directory)
494
```
495
496
**Usage Example:**
497
498
```java
499
// Place custom configuration files in src/test/resources/mariadb-config/
500
// Files like custom.cnf will be mounted to /etc/mysql/conf.d/
501
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
502
.withConfigurationOverride("mariadb-config");
503
```
504
505
## Error Handling
506
507
Common exceptions and troubleshooting guide for MariaDB container issues:
508
509
### SQLException: No suitable driver found
510
511
**Cause**: MariaDB JDBC driver not in classpath.
512
513
**Solution**: Add the MariaDB JDBC driver dependency:
514
```groovy
515
testImplementation 'org.mariadb.jdbc:mariadb-java-client:3.4.1'
516
```
517
518
### ContainerLaunchException
519
520
**Cause**: Container failed to start (Docker issues, port conflicts, resource constraints).
521
522
**Solutions**:
523
```java
524
// Increase startup timeout for slow environments
525
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
526
.withStartupTimeoutSeconds(300);
527
528
// Check Docker daemon status and available resources
529
// Ensure port 3306 is not in use by another process
530
```
531
532
### Container startup timeout
533
534
**Cause**: Container takes too long to become ready.
535
536
**Solutions**:
537
```java
538
// Increase timeout and retry attempts
539
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
540
.withStartupTimeoutSeconds(600)
541
.withStartupAttempts(3);
542
```
543
544
### Connection timeout or refused
545
546
**Cause**: Database not ready or connection configuration issues.
547
548
**Solutions**:
549
```java
550
// Increase connection timeout
551
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
552
.withConnectTimeoutSeconds(120);
553
554
// Verify container is running before connecting
555
assertTrue(mariadb.isRunning());
556
557
// Use container-provided connection details
558
String jdbcUrl = mariadb.getJdbcUrl(); // Don't hardcode connection details
559
```
560
561
### Permission denied (configuration files)
562
563
**Cause**: Custom configuration files have wrong permissions.
564
565
**Solution**:
566
```java
567
// Ensure configuration directory is readable
568
// Set proper file permissions on src/test/resources/mariadb-config/
569
// Use try-with-resources for proper cleanup
570
```
571
572
### Empty password error
573
574
**Cause**: Non-root user with empty password.
575
576
**Solution**:
577
```java
578
// Only root user can have empty password
579
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
580
.withUsername("root"); // Empty password allowed for root
581
582
// For other users, always provide password
583
MariaDBContainer<?> mariadb = new MariaDBContainer<>("mariadb:10.3.39")
584
.withUsername("testuser")
585
.withPassword("testpass"); // Required for non-root users
586
```
587
588
## Constants
589
590
```java { .api }
591
public static final String NAME = "mariadb"; // Container type identifier
592
public static final Integer MARIADB_PORT = 3306; // MariaDB default port
593
// Note: DEFAULT_USER and DEFAULT_PASSWORD are package-private, not public API
594
595
@Deprecated
596
public static final String DEFAULT_TAG = "10.3.6"; // Deprecated default version
597
@Deprecated
598
public static final String IMAGE = "mariadb"; // Deprecated image name
599
```