1515import org .junit .rules .ExternalResource ;
1616import org .testcontainers .containers .BindMode ;
1717import org .testcontainers .containers .GenericContainer ;
18+ import org .testcontainers .containers .InternetProtocol ;
1819import org .testcontainers .containers .Network ;
20+ import org .testcontainers .containers .wait .strategy .Wait ;
1921
2022import java .io .File ;
2123import java .io .IOException ;
@@ -26,8 +28,10 @@ public class MySQLRule extends ExternalResource {
2628 private static final String connectionUri = System .getProperty ("connection.uri" );
2729 private static final String tlsConnectionUri = System .getProperty ("tls.connection.uri" );
2830
31+ private static final int DEFAULT_PORT = 3306 ;
32+
2933 private Network network ;
30- private GenericContainer <?> server ;
34+ private ServerContainer <?> server ;
3135 private MySQLConnectOptions options ;
3236 private DatabaseServerInfo databaseServerInfo ;
3337 private File mysqldDir ;
@@ -67,7 +71,7 @@ public synchronized void stopServer() throws Exception {
6771 private void initServer () throws IOException {
6872 network = Network .builder ().driver ("bridge" ).build ();
6973
70- server = new GenericContainer <>(databaseServerInfo .getDatabaseType ().toDockerImageName () + ":" + databaseServerInfo .getDockerImageTag ())
74+ server = new ServerContainer <>(databaseServerInfo .getDatabaseType ().toDockerImageName () + ":" + databaseServerInfo .getDockerImageTag ())
7175 .withEnv ("MYSQL_USER" , "mysql" )
7276 .withEnv ("MYSQL_PASSWORD" , "password" )
7377 .withEnv ("MYSQL_ROOT_PASSWORD" , "password" )
@@ -78,9 +82,15 @@ private void initServer() throws IOException {
7882 })
7983 .withNetwork (network )
8084 .withNetworkAliases (networkAlias ())
81- .withExposedPorts (3306 )
8285 .withClasspathResourceMapping ("init.sql" , "/docker-entrypoint-initdb.d/init.sql" , BindMode .READ_ONLY )
83- .withReuse (true );
86+ .waitingFor (Wait .forLogMessage (".*ready for connections.*\\ n" , databaseServerInfo .getDatabaseType () == DatabaseType .MariaDB ? 2 : 4 ));
87+
88+ if (System .getProperties ().containsKey ("containerFixedPort" )) {
89+ server .withFixedExposedPort (DEFAULT_PORT , DEFAULT_PORT );
90+ } else {
91+ server .withExposedPorts (DEFAULT_PORT );
92+ }
93+
8494
8595 mysqldDir = Files .createTempDirectory ("mysqld" ).toFile ();
8696 mysqldDir .deleteOnExit ();
@@ -273,4 +283,16 @@ public static DatabaseServerInfo valueOf(DatabaseType databaseType, String docke
273283 }
274284 }
275285 }
286+
287+ private static class ServerContainer <SELF extends ServerContainer <SELF >> extends GenericContainer <SELF > {
288+
289+ public ServerContainer (String dockerImageName ) {
290+ super (dockerImageName );
291+ }
292+
293+ public SELF withFixedExposedPort (int hostPort , int containerPort ) {
294+ super .addFixedExposedPort (hostPort , containerPort , InternetProtocol .TCP );
295+ return self ();
296+ }
297+ }
276298}
0 commit comments