Recommended Free Tools
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To select one service from a Compose file with Testcontainers’ legacy DockerComposeContainer API, call .withServices("redis"). Register its container port with .withExposedService(...), start the environment, then use Testcontainers’ mapped host and port. This selects a Compose service; dependencies or replicas may still result in more than one container.
Version note: DockerComposeContainer uses the older Docker Compose V1 integration. Testcontainers documents ComposeContainer as the option for Compose V2, so use that newer API for a new or upgraded project. See the Testcontainers Compose documentation.
Minimal example: select Redis, not Postgres
Suppose src/test/resources/docker-compose.yml defines two services:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchservices:
redis:
image: redis:7-alpine
postgres:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: test
The Java test can select only the Redis service. It does not need a fixed host-port mapping in the Compose file; Testcontainers makes the exposed service reachable through a dynamically mapped port.
#1 Best Overall
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.DockerImageName;
import java.io.File;
import java.time.Duration;
class RedisComposeTest {
@Test
void startOnlyRedis() {
try (DockerComposeContainer<?> environment =
new DockerComposeContainer<>(
DockerImageName.parse("docker:25.0.5"),
new File("src/test/resources/docker-compose.yml"))
.withServices("redis")
.withExposedService(
"redis",
6379,
Wait.forListeningPort()
.withStartupTimeout(Duration.ofSeconds(60)))) {
environment.start();
String host = environment.getServiceHost("redis", 6379);
Integer port = environment.getServicePort("redis", 6379);
System.out.println("Redis: " + host + ":" + port);
// Configure your Redis client with host and port here.
}
}
}
The docker:25.0.5 image is part of the legacy containerized Compose setup; it is an example, not a recommendation that every project use that exact Docker version. Choose a Testcontainers release and Docker/Compose setup that match your project and CI environment.
The two configuration calls have different jobs:
.withServices("redis")selects the Compose service or services Testcontainers should launch..withExposedService("redis", 6379)tells Testcontainers which service port to wait for and make available to the test process.
Calling only withExposedService is not the explicit way to restrict the selected service set. The DockerComposeContainer API provides both methods. Pass multiple service names when the test needs more than one:
.withServices("redis", "postgres")
Use the mapped endpoint, not a presumed localhost port
Port 6379 is Redis’s port inside its container. The port available to the Java process may be different. Retrieve both endpoint values after startup:
String host = environment.getServiceHost("redis", 6379);
Integer port = environment.getServicePort("redis", 6379);
Use those values to configure your client, for example by constructing a connection URI from the returned host and port. The service must be registered with withExposedService, and the environment must be started before requesting its endpoint. Avoid adding ports: ["6379:6379"] just for this test: Testcontainers’ Compose integration proxies exposed service ports, so a fixed host mapping is usually unnecessary and can collide with another process.
Readiness: a running container may not be ready for your test
The example uses Wait.forListeningPort() and gives it a 60-second startup timeout. The Testcontainers documentation describes an ordinary wait of up to 60 seconds for an exposed service’s first mapped port to begin listening. A listening port does not prove that Redis responds correctly, a database accepts queries, migrations have completed, or authentication is ready.
Choose a readiness condition that reflects what the test actually needs. Testcontainers documents port-, log-, and command-based waits; the appropriate command and its execution context depend on the image and Testcontainers version. For example, a command-level check might be configured as:
.withExposedService(
"redis",
6379,
Wait.forSuccessfulCommand("redis-cli ping")
.withStartupTimeout(Duration.ofSeconds(90)))
Use this only if the selected image provides redis-cli and the command runs successfully in the context expected by your Compose integration. A log-message wait can be more suitable for services that emit a reliable ready message. Consult the documented wait strategies for the API available in your release.
Free tools Windows power users keep installed
One-click scans. No signup required.
Manage the Testcontainers lifecycle
The try-with-resources example closes the environment when the block exits, including when the test throws. You can also let the JUnit Testcontainers extension manage a static container for the test class:
Rank #3
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.io.File;
@Testcontainers
class RedisComposeTest {
@Container
static DockerComposeContainer<?> environment =
new DockerComposeContainer<>(
DockerImageName.parse("docker:25.0.5"),
new File("src/test/resources/docker-compose.yml"))
.withServices("redis")
.withExposedService("redis", 6379);
@Test
void testRedis() {
String host = environment.getServiceHost("redis", 6379);
Integer port = environment.getServicePort("redis", 6379);
// Exercise Redis using the mapped endpoint.
}
}
This static-field pattern starts the environment for the class and lets the extension stop it afterward. Confirm that your JUnit integration dependency and annotations match the JUnit and Testcontainers versions used by your project.
One selected service can still bring dependencies
withServices("redis") selects a Compose service, not a guarantee of exactly one container. If the selected service declares depends_on, Compose may also start its dependencies; replicas or other Compose behavior can also produce additional containers. For example, selecting api from a file where it depends on postgres may require Postgres to start for the application to function.
If more services start than expected, check the Compose dependency graph and whether old containers are still present. Inspect the running containers and project state:
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →docker compose ps
docker ps --format '{{.Names}}'
For a disposable local project, clean up its containers and orphans before rerunning:
docker compose down --remove-orphans
Use the same Compose project context when inspecting or cleaning up; avoid removing resources belonging to other work.
Service names and generated container names are not always the same
The YAML service key is redis. Compose may create a container with a generated name such as redis_1 or redis-1, depending on the Compose generation and integration. The value accepted by a particular Testcontainers method can likewise depend on the API and version.
For the legacy example, use the service key consistently, then check the generated names if Testcontainers reports that it cannot find or expose the service. The command docker ps --format '{{.Names}}' shows actual running container names. Do not mechanically replace redis with a suffixed name without checking the API’s expected identifier.
In its Compose V2 guidance, Testcontainers shows names such as redis-1 for ComposeContainer exposed-service configuration and warns to use a hyphen rather than an underscore in that context. Follow the Compose V2 examples when migrating; do not assume the V2 naming form applies unchanged to the legacy API.
Best Value
- Docker, Docker Swarm, Docker Compose, Programmer, Developer, Coding, Programming, Software Engineer, Code, DevOps, Deploy, Deployment, Kubernetes, Salt, Puppet, Chef, Terraform, Container, AWS, Azure, Cloud, Geek, Funny, Computer, Software, Tech, IT
- Integration, Scrum, Compile, Compilation, Science, Bug, Debug, Python, Linux, Java, Javascript, Scala, Dotnet, Kotlin
- Lightweight, Classic fit, Double-needle sleeve and bottom hem
DockerComposeContainer versus ComposeContainer
DockerComposeContainer is the older Testcontainers integration for Compose V1. Docker distinguishes the old docker-compose command from the current docker compose CLI, and Testcontainers documents ComposeContainer as its Compose V2 integration. The Java class should not be described as removed solely on that basis, but it is a legacy choice for projects using current Compose.
For a new project or a migration to Compose V2, use org.testcontainers.containers.ComposeContainer and follow its current constructor, naming, and exposed-service conventions. A schematic setup looks like this; verify the service identifier against the documentation for the version in your build:
ComposeContainer environment = new ComposeContainer(
DockerImageName.parse("docker:25.0.5"),
new File("src/test/resources/compose.yml"))
.withExposedService("redis-1", 6379);
The exact selection and naming configuration should follow the Compose V2 API examples for the Testcontainers release you use. Do not copy legacy DockerComposeContainer assumptions into a migration without checking those differences.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
When the command line is enough
For local development, the Docker Compose CLI may be simpler than embedding Compose in a Java test. On a fresh project, docker compose up -d redis creates and starts the selected service; docker compose start redis only starts an already-created stopped container and does not create one. The Docker start reference documents that distinction. docker compose run creates a one-off container rather than starting the normal service, and does not publish the service’s ports by default; see the run reference.
Use Testcontainers when the test needs Java-managed startup and cleanup, a dynamically mapped endpoint, and a readiness check. If the Compose file contributes little beyond one image and a few settings, a GenericContainer may be a simpler fit. If it captures useful configuration or dependencies, keeping a test-focused Compose file can be more maintainable.
Troubleshooting
- Docker is unavailable: Testcontainers needs access to a Docker daemon. That may be Docker Desktop, Docker Engine, a remote daemon, or a CI-provided Docker service/socket; setup varies by platform and CI provider.
- Endpoint lookup fails: Check that the service and internal container port match the values passed to
withExposedService, that startup completed, and that endpoint lookup occurs afterward. - The service times out: Check container logs and image-specific startup requirements. Increase the timeout only if startup legitimately takes longer; prefer an application-level readiness check when an open port is insufficient.
- The image uses
build:: The legacy API provides.withBuild(true)to force images to be built before startup. Verify the method against your Testcontainers version and that the build context is correct. - A private image cannot be pulled: Containerized Compose may need Docker registry credentials. Testcontainers documents
DOCKER_CONFIG_FILE=/path/to/config.jsonor the JVM property-DdockerConfigFile=/path/to/config.jsonfor Docker configuration. - Unexpected services appear: Check
depends_on, replicas, the Compose project’s existing containers, and whether.withServices(...)is present. Clean up only the intended project’s stale resources.
For constructor and method details, use the 2.0.5 DockerComposeContainer Javadoc; for integration behavior and the modern alternative, use the Testcontainers Compose module documentation. The 2.0.5 Javadoc is a version-specific API reference, not a requirement to upgrade to that release.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errors

