The Testcontainers Elasticsearch module provides a specialized container implementation for running Elasticsearch instances in Docker containers during testing. It enables Java developers to write integration tests against real Elasticsearch instances by automatically managing container lifecycle, port mappings, and configuration.
Required Dependencies:
org.testcontainers:elasticsearch (this package, version 1.21.4)org.testcontainers:testcontainers core library is required (provided transitively)org.elasticsearch.client:elasticsearch-rest-client or co.elastic.clients:elasticsearch-java) for connecting to the container (not required by testcontainers itself)Default Behaviors:
9200 (exposed and mapped to random host port)9300 (exposed, deprecated in ES 8.x)single-node (Elasticsearch runs in single-node mode)cluster.routing.allocation.disk.threshold_enabled=false)2GB (configurable via ES_JAVA_OPTS)docker.elastic.co/elasticsearch/elasticsearch:7.9.2 or 8.1.2)"changeme" (username: "elastic")withPassword())getHttpHostAddress() or getMappedPort(9200) to retrieve)Threading Model:
ElasticsearchContainer instances are not thread-safe for concurrent modificationstart(), stop(), close()) are not thread-safegetHttpHostAddress(), getMappedPort()) are safe from multiple threadsLifecycle:
container.start() before usecontainer.stop() or container.close() for cleanupAutoCloseable - use try-with-resources for automatic cleanupwithPassword(), withCertPath()) must be called before start()getHttpHostAddress(), createSslContextFromCa()) must be called after start()Exceptions:
ContainerLaunchException - Container failed to startIllegalArgumentException - Invalid configuration (e.g., withPassword() on OSS image)IllegalStateException - Operation on container in invalid state (e.g., caCertAsBytes() when certificate not available, or calling access methods before start())RuntimeException - SSL/certificate errors, Docker errors, or other runtime issuesTimeoutException - Startup timeout exceededDockerException - Docker daemon not available or image pull failedEdge Cases:
getHttpHostAddress() to get actual endpoint)waitingFor() with custom wait strategy)ES_JAVA_OPTS environment variable)start() is called (default is "changeme")createSslContextFromCa() for HTTPS connectionswithPassword() with OSS images (throws IllegalArgumentException)withNetworkMode() or withNetwork()withClasspathResourceMapping() or withCopyToContainer() for persistent setup)getHttpHostAddress() before start(): Throws IllegalStateExceptioncreateSslContextFromCa() on ES 7.x: May throw IllegalStateException if certificate not availablewithPassword("") may cause authentication failureswithCertPath() must be called before start() and path must exist in containergetLogs() after container startsexecInContainer() can be used after container startsGradle:
testImplementation "org.testcontainers:elasticsearch:1.21.4"Maven:
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>elasticsearch</artifactId>
<version>1.21.4</version>
<scope>test</scope>
</dependency>import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.testcontainers.utility.DockerImageName;The ElasticsearchContainer class extends GenericContainer<ElasticsearchContainer> from the Testcontainers core library, inheriting all standard container lifecycle and configuration methods. It provides Elasticsearch-specific functionality including:
Create Elasticsearch container instances with version-specific Docker images.
package org.testcontainers.elasticsearch;
public class ElasticsearchContainer extends GenericContainer<ElasticsearchContainer> {
/**
* @deprecated Use ElasticsearchContainer(DockerImageName) instead
*/
@Deprecated
public ElasticsearchContainer();
public ElasticsearchContainer(String dockerImageName);
public ElasticsearchContainer(DockerImageName dockerImageName);
}Parameters:
dockerImageName (String or DockerImageName): Full docker image name, e.g., "docker.elastic.co/elasticsearch/elasticsearch:7.9.2" or "docker.elastic.co/elasticsearch/elasticsearch:8.1.2"Returns: ElasticsearchContainer instance (not started)
Supported Images:
docker.elastic.co/elasticsearch/elasticsearch (recommended)docker.elastic.co/elasticsearch/elasticsearch-oss (deprecated after 7.10.2, no security features)elasticsearch (Docker Hub)Default Configuration Applied:
discovery.type=single-node)cluster.routing.allocation.disk.threshold_enabled=false)Example:
// Recommended approach with DockerImageName
DockerImageName image = DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch:7.9.2");
ElasticsearchContainer container = new ElasticsearchContainer(image);
// Also valid with String
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
);Enable and configure security features including authentication and password management.
public ElasticsearchContainer withPassword(String password);Parameters:
password (String): Password to set for the 'elastic' user (non-null, non-empty recommended)Returns: ElasticsearchContainer for method chaining
When to Call: Must be called before start()
Description:
IllegalArgumentException)Throws:
IllegalArgumentException - If called with OSS image or invalid configurationExample:
// Elasticsearch 7.x with security enabled
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)
.withPassword("mysecretpassword");
container.start();
// Create authenticated REST client
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "mysecretpassword")
);
RestClient client = RestClient
.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
)
.build();Get the HTTP endpoint address for connecting to Elasticsearch.
public String getHttpHostAddress();Returns: String in format "host:port" (e.g., "localhost:32768")
When to Call: Must be called after start() completes
Description: Returns the host and dynamically mapped port for the Elasticsearch HTTP endpoint (port 9200). Use this to construct HTTP clients for connecting to the Elasticsearch instance.
Throws:
IllegalStateException - If called before container is startedExample:
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
String endpoint = container.getHttpHostAddress();
// endpoint = "localhost:32768" (port varies)
RestClient client = RestClient.builder(HttpHost.create(endpoint)).build();Extract and use SSL certificates for HTTPS connections to Elasticsearch 8.x+ instances.
public Optional<byte[]> caCertAsBytes();
public SSLContext createSslContextFromCa();
public ElasticsearchContainer withCertPath(String certPath);caCertAsBytes():
Optional<byte[]> containing CA certificate bytes, or empty if not availablestart() completescreateSslContextFromCa():
SSLContext configured to trust the container's CA certificatestart() completesIllegalStateException - If CA certificate not found (ES version < 8.x or certificate path invalid)RuntimeException - For SSL/certificate errorswithCertPath(String certPath):
certPath - Path to CA certificate within the Docker container (non-null)ElasticsearchContainer for method chainingstart()/usr/share/elasticsearch/config/certs/http_ca.crt)Example:
// Elasticsearch 8.x with HTTPS
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
);
container.start();
// Create HTTPS client with SSL context
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
);
RestClient client = RestClient
.builder(HttpHost.create("https://" + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
return httpClientBuilder;
})
.build();
// Optionally get certificate bytes
Optional<byte[]> certBytes = container.caCertAsBytes();
if (certBytes.isPresent()) {
// Use certificate bytes for custom SSL configuration
}Get the transport client endpoint for legacy TransportClient connections.
/**
* @deprecated The TransportClient is removed in Elasticsearch 8
*/
@Deprecated
public InetSocketAddress getTcpHost();Returns: InetSocketAddress with host and mapped transport port (9300)
When to Call: Must be called after start() completes
Description: Returns the endpoint for the deprecated TransportClient API. The TransportClient was removed in Elasticsearch 8.x. Use the REST client instead.
Throws:
IllegalStateException - If called before container is startedExample (for Elasticsearch 7.x only):
@SuppressWarnings("deprecation")
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
TransportAddress transportAddress = new TransportAddress(container.getTcpHost());
Settings settings = Settings.builder().put("cluster.name", "docker-cluster").build();
TransportClient transportClient = new PreBuiltTransportClient(settings)
.addTransportAddress(transportAddress);/**
* Default password constant for Elasticsearch 8.x+
*/
public static final String ELASTICSEARCH_DEFAULT_PASSWORD = "changeme";import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.Request;
// Create and start container with Elasticsearch 7.x
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
// Get HTTP endpoint
String httpHostAddress = container.getHttpHostAddress();
// Create REST client and use it
RestClient client = RestClient.builder(HttpHost.create(httpHostAddress)).build();
client.performRequest(new Request("GET", "/"));
// Container is automatically stopped when closed (try-with-resources)
client.close();
container.close();Use try-with-resources for automatic cleanup:
try (ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)) {
container.start();
// Use container for tests
RestClient client = RestClient
.builder(HttpHost.create(container.getHttpHostAddress()))
.build();
// Perform operations
client.performRequest(new Request("GET", "/_cluster/health"));
client.close();
} // Container automatically stopped and removedimport org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
// Elasticsearch 8.x with HTTPS
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
);
container.start();
// Create HTTPS client with SSL context
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
);
RestClient client = RestClient
.builder(HttpHost.create("https://" + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
return httpClientBuilder;
})
.build();
// Use the client
client.performRequest(new Request("GET", "/"));
client.close();
container.close();import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
// Elasticsearch 7.x with security enabled
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)
.withPassword("mysecretpassword");
container.start();
// Create authenticated REST client
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "mysecretpassword")
);
RestClient client = RestClient
.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
)
.build();
client.performRequest(new Request("GET", "/"));
client.close();
container.close();import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.apache.http.HttpHost;
import static org.junit.jupiter.api.Assertions.*;
class ElasticsearchIntegrationTest {
private ElasticsearchContainer container;
private RestClient client;
@BeforeEach
void setUp() {
container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
client = RestClient.builder(
HttpHost.create(container.getHttpHostAddress())
).build();
}
@AfterEach
void tearDown() throws Exception {
if (client != null) {
client.close();
}
if (container != null) {
container.close();
}
}
@Test
void testClusterHealth() throws Exception {
Response response = client.performRequest(new Request("GET", "/_cluster/health"));
assertEquals(200, response.getStatusLine().getStatusCode());
}
@Test
void testIndexCreation() throws Exception {
Request request = new Request("PUT", "/test-index");
Response response = client.performRequest(request);
assertEquals(200, response.getStatusLine().getStatusCode());
}
}import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.apache.http.HttpHost;
import static org.junit.Assert.*;
public class ElasticsearchIntegrationTest {
private ElasticsearchContainer container;
private RestClient client;
@Before
public void setUp() {
container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
client = RestClient.builder(
HttpHost.create(container.getHttpHostAddress())
).build();
}
@After
public void tearDown() throws Exception {
if (client != null) {
client.close();
}
if (container != null) {
container.close();
}
}
@Test
public void testClusterHealth() throws Exception {
Response response = client.performRequest(new Request("GET", "/_cluster/health"));
assertEquals(200, response.getStatusLine().getStatusCode());
}
}Disable SSL for testing environments where HTTPS is not required:
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
)
.withEnv("xpack.security.transport.ssl.enabled", "false")
.withEnv("xpack.security.http.ssl.enabled", "false");
container.start();
// Use HTTP instead of HTTPS
RestClient client = RestClient
.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
);
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();Configure JVM heap size via environment variable:
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)
.withEnv("ES_JAVA_OPTS", "-Xms1g -Xmx1g");
container.start();Or via JVM options file:
import org.testcontainers.containers.BindMode;
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)
.withClasspathResourceMapping(
"custom-jvm.options",
"/usr/share/elasticsearch/config/jvm.options.d/custom-jvm.options",
BindMode.READ_ONLY
);
container.start();Override the default wait strategy with HTTP-based waiting for Elasticsearch 8.x:
import org.testcontainers.containers.wait.strategy.Wait;
import java.time.Duration;
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
)
.waitingFor(
Wait.forHttps("/")
.forPort(9200)
.forStatusCode(200)
.withBasicCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
.allowInsecure() // Trust self-signed certificate
.withStartupTimeout(Duration.ofSeconds(300))
);
container.start();Run multiple Elasticsearch containers concurrently:
ElasticsearchContainer container1 = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
ElasticsearchContainer container2 = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
);
container1.start();
container2.start();
// Each container gets unique ports
String endpoint1 = container1.getHttpHostAddress();
String endpoint2 = container2.getHttpHostAddress();
// Use containers independently
RestClient client1 = RestClient.builder(HttpHost.create(endpoint1)).build();
RestClient client2 = RestClient.builder(HttpHost.create(endpoint2)).build();
// Cleanup
client1.close();
client2.close();
container1.close();
container2.close();import org.testcontainers.containers.Network;
Network network = Network.newNetwork();
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)
.withNetwork(network);
container.start();ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
)
.withCertPath("/custom/path/to/certificate.crt");
container.start();The ElasticsearchContainer inherits all methods from GenericContainer<ElasticsearchContainer>, providing extensive container management capabilities:
Lifecycle Management:
void start() - Start the container (blocks until ready)void stop() - Stop the containervoid close() - Stop and remove the container (AutoCloseable)Environment Configuration:
ElasticsearchContainer withEnv(String key, String value) - Set environment variableElasticsearchContainer withEnv(Map<String, String> env) - Set multiple environment variablesFile Operations:
ElasticsearchContainer withClasspathResourceMapping(String resourcePath, String containerPath, BindMode mode) - Mount classpath resourceElasticsearchContainer withCopyToContainer(Transferable transferable, String containerPath) - Copy content to containervoid copyFileFromContainer(String containerPath, Consumer<InputStream> consumer) - Copy file from containerNetwork Configuration:
ElasticsearchContainer withExposedPorts(Integer... ports) - Expose additional portsInteger getMappedPort(int originalPort) - Get dynamically mapped portString getHost() - Get container host (typically "localhost")ElasticsearchContainer withNetwork(Network network) - Attach to specific networkElasticsearchContainer withNetworkMode(String networkMode) - Set network mode (e.g., "host", "bridge")Wait Strategies:
ElasticsearchContainer waitingFor(WaitStrategy waitStrategy) - Set custom wait strategyElasticsearchContainer setWaitStrategy(WaitStrategy waitStrategy) - Alternative wait strategy setterCommand Execution:
ElasticsearchContainer withCommand(String... commandParts) - Override container commandContainer.ExecResult execInContainer(String... command) - Execute command in running containerLogging:
ElasticsearchContainer withLogConsumer(Consumer<OutputFrame> consumer) - Configure log consumptionString getLogs() - Get container logs as stringString getLogs(OutputFrame.OutputType... types) - Get filtered container logsAnd many more standard container operations available in the Testcontainers GenericContainer API.
withPassword() to enable X-Pack securitydocker-clusterElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD ("changeme")createSslContextFromCa() for HTTPS connectionstry {
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
// Use container
} catch (ContainerLaunchException e) {
// Container failed to start
// Check Docker daemon, image availability, system resources
System.err.println("Container failed to start: " + e.getMessage());
e.printStackTrace();
} catch (TimeoutException e) {
// Startup timeout exceeded
// Increase timeout or check system performance
System.err.println("Startup timeout: " + e.getMessage());
e.printStackTrace();
} catch (DockerException e) {
// Docker daemon not available or image pull failed
// Check Docker daemon status, network connectivity
System.err.println("Docker error: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
// Other unexpected errors
System.err.println("Unexpected error: " + e.getMessage());
e.printStackTrace();
}ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
);
container.start();
try {
RestClient client = RestClient
.builder(HttpHost.create("https://" + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
);
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
return httpClientBuilder;
})
.build();
client.performRequest(new Request("GET", "/"));
client.close();
} catch (ResponseException e) {
if (e.getResponse().getStatusLine().getStatusCode() == 401) {
// Authentication failed
// Verify password matches expected value
System.err.println("Authentication failed - check password");
} else {
System.err.println("Request failed: " + e.getMessage());
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
container.close();
}try {
SSLContext sslContext = container.createSslContextFromCa();
// Use SSL context
} catch (IllegalStateException e) {
// CA certificate not found
// Check if using Elasticsearch 8.x+, verify certificate path
System.err.println("Certificate not found: " + e.getMessage());
// Verify ES version is 8.x+ and certificate path is correct
} catch (RuntimeException e) {
// SSL/certificate errors
// Check certificate validity, SSL configuration
System.err.println("SSL error: " + e.getMessage());
e.printStackTrace();
}try {
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch-oss:7.9.2" // OSS image
)
.withPassword("mypassword"); // This will throw IllegalArgumentException
container.start();
} catch (IllegalArgumentException e) {
// withPassword() not available for OSS images
// Use default distribution instead
System.err.println("Invalid configuration: " + e.getMessage());
// Solution: Use docker.elastic.co/elasticsearch/elasticsearch:7.9.2 instead
}Solution: Use HTTPS instead of HTTP and configure SSL context:
RestClient client = RestClient
.builder(HttpHost.create("https://" + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setSSLContext(container.createSslContextFromCa())
)
.build();Solution: Provide credentials (default username is "elastic"):
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
);Solution: Use the default distribution instead:
// Instead of elasticsearch-oss image, use:
new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:7.9.2")
.withPassword("mypassword");Solution: Ensure Docker has adequate resources allocated. Elasticsearch requires at least 2GB RAM (configured by default). You can also increase the startup timeout:
import org.testcontainers.containers.wait.strategy.Wait;
import java.time.Duration;
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
)
.waitingFor(Wait.forHttp("/").withStartupTimeout(Duration.ofSeconds(300)));
container.start();Solution: Use createSslContextFromCa() method to create SSL context:
SSLContext sslContext = container.createSslContextFromCa();
// Use in HTTP client configurationSolution: Container automatically maps to random ports. Use getHttpHostAddress() to get the actual endpoint:
String endpoint = container.getHttpHostAddress(); // Returns "localhost:32768" (varies)Solution: Always call start() before accessing container endpoints:
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start(); // Must call start() first
String endpoint = container.getHttpHostAddress(); // Now safe to callSolution: SSL context methods are only available for Elasticsearch 8.x+. For ES 7.x, use HTTP without SSL:
// For ES 7.x, use HTTP
RestClient client = RestClient.builder(
HttpHost.create(container.getHttpHostAddress())
).build();import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.apache.http.HttpHost;
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:7.9.2"
);
container.start();
RestClient client = RestClient.builder(
HttpHost.create(container.getHttpHostAddress())
).build();
// Perform requests
Request request = new Request("GET", "/_cluster/health");
Response response = client.performRequest(request);
client.close();
container.close();import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
);
container.start();
// For ES 8.x with HTTPS
RestClient restClient = RestClient
.builder(HttpHost.create("https://" + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD)
);
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
return httpClientBuilder;
})
.build();
ElasticsearchClient client = new ElasticsearchClient(
new RestClientTransport(restClient, new JacksonJsonpMapper())
);
// Use the client
client.indices().create(c -> c.index("test-index"));
restClient.close();
container.close();container.close() when donecontainer.getLogs() methodcontainer.execInContainer()createSslContextFromCa() for connectionsstart()start() completes