44import com .github .dockerjava .api .command .InspectContainerResponse ;
55import com .github .dockerjava .core .command .ExecStartResultCallback ;
66import lombok .SneakyThrows ;
7+ import org .testcontainers .images .builder .Transferable ;
78import org .testcontainers .utility .TestcontainersConfiguration ;
89
10+ import java .nio .charset .StandardCharsets ;
911import java .util .concurrent .TimeUnit ;
12+ import java .util .stream .Collectors ;
13+ import java .util .stream .Stream ;
1014
1115/**
1216 * This container wraps Confluent Kafka and Zookeeper (optionally)
1317 *
1418 */
1519public class KafkaContainer extends GenericContainer <KafkaContainer > {
1620
21+ private static final String STARTER_SCRIPT = "/testcontainers_start.sh" ;
22+
1723 public static final int KAFKA_PORT = 9093 ;
1824
1925 public static final int ZOOKEEPER_PORT = 2181 ;
@@ -97,7 +103,7 @@ public String getBootstrapServers() {
97103
98104 @ Override
99105 protected void doStart () {
100- withCommand ("sleep infinity" );
106+ withCommand ("sh" , "-c" , "while [ ! -f " + STARTER_SCRIPT + " ]; do sleep 0.1; done; " + STARTER_SCRIPT );
101107
102108 if (externalZookeeperConnect == null ) {
103109 addExposedPort (ZOOKEEPER_PORT );
@@ -124,17 +130,24 @@ protected void containerIsStarting(InspectContainerResponse containerInfo, boole
124130 zookeeperConnect = startZookeeper ();
125131 }
126132
127- String internalIp = containerInfo . getNetworkSettings (). getIpAddress () ;
128-
129- ExecCreateCmdResponse execCreateCmdResponse = dockerClient . execCreateCmd ( getContainerId ())
130- .withCmd ( "sh" , "-c" , "" +
131- "export KAFKA_ZOOKEEPER_CONNECT=" + zookeeperConnect + " \n " +
132- "export KAFKA_ADVERTISED_LISTENERS=" + getBootstrapServers () + "," + String . format ( "BROKER://%s:9092" , internalIp ) + " \n " +
133- "/etc/confluent/docker/run"
133+ String command = "#!/bin/bash \n " ;
134+ command += "export KAFKA_ZOOKEEPER_CONNECT='" + zookeeperConnect + "' \n " ;
135+ command += "export KAFKA_ADVERTISED_LISTENERS='" + Stream
136+ .concat (
137+ Stream . of ( getBootstrapServers ()),
138+ containerInfo . getNetworkSettings (). getNetworks (). values (). stream ()
139+ . map ( it -> "BROKER://" + it . getIpAddress () + ":9092" )
134140 )
135- .exec () ;
141+ .collect ( Collectors . joining ( "," )) + "' \n " ;
136142
137- dockerClient .execStartCmd (execCreateCmdResponse .getId ()).exec (new ExecStartResultCallback ()).awaitStarted (10 , TimeUnit .SECONDS );
143+ command += ". /etc/confluent/docker/bash-config \n " ;
144+ command += "/etc/confluent/docker/configure \n " ;
145+ command += "/etc/confluent/docker/launch \n " ;
146+
147+ copyFileToContainer (
148+ Transferable .of (command .getBytes (StandardCharsets .UTF_8 ), 700 ),
149+ STARTER_SCRIPT
150+ );
138151 }
139152
140153 @ SneakyThrows (InterruptedException .class )
0 commit comments