Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Show how to start an application locally with a Postgres Testcontainer instead of a manually installed database.

We add a second main class under src/test, usually called TestApplication, that calls SpringApplication.from(Application::main).with(ContainersConfig.class).run(args). ContainersConfig is a @TestConfiguration that declares a PostgreSQLContainer as a @Bean annotated with @ServiceConnection, so Boot starts the container and connects the DataSource to it without any properties. We run it with mvn spring-boot:test-run or gradle bootTestRun, and add @RestartScope to the container bean so it survives DevTools restarts.

Why this question is asked

Installing PostgreSQL on every developer machine sounds simple until the versions differ, a migration leaves one laptop in a strange state, or a new joiner spends half a day on it. Since Spring Boot 3.1, we can start the application locally with the same Testcontainers setup our integration tests already use. Interviewers ask for this as a coding question because it touches several newer Boot features at once: service connections, starting an application from another main method, and container lifecycle with DevTools. In this answer, we will recap Testcontainers and service connections, write the container configuration, write the test application class, run it, and then keep the container alive across restarts.

1A Quick Recap: Testcontainers and Service Connections

Testcontainers is a Java library that starts Docker containers from code. We create an object such as PostgreSQLContainer, start it, and ask it for its JDBC URL, user and password; when the JVM ends, the container is removed. It is mostly used in integration tests, so each test run gets a clean, real database.

A service connection is Spring Boot's way of describing how to reach a service as a ConnectionDetails bean, instead of properties like spring.datasource.url. When a container bean is annotated with @ServiceConnection, Boot reads the container's connection information and creates the matching ConnectionDetails, such as JdbcConnectionDetails for PostgreSQL, which the DataSource auto-configuration uses. That is why no properties are needed.

XML
<!-- pom.xml: all test scope, none of it reaches the production jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId> <!-- testcontainers-postgresql in Testcontainers 2.x -->
<scope>test</scope>
</dependency>

Testcontainers 2, used with Spring Boot 4, renamed its module artifacts and moved some classes to new packages, so check your version for the exact artifact and import.

2Declare the Container as a Bean

We put the container in a configuration class under src/test/java, so it is never part of the application itself. The class is a @TestConfiguration, which means component scanning does not pick it up by accident; it is only used where we import it. Inside, a @Bean method returns the container, and @ServiceConnection tells Boot to derive the connection details from it.

Java
// src/test/java/com/acme/orders/ContainersConfig.java
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
@Bean
@ServiceConnection // Boot creates JdbcConnectionDetails from this container
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>(DockerImageName.parse("postgres:17"));
}
}
// Notice: no start() call. Boot starts container beans before the beans that use them.

Notice that we do not call start() ourselves. Spring Boot manages container beans: it starts them when the context starts, before any bean that needs the connection, and stops them when the context closes. We also pin the image tag, postgres:17, to match production rather than using latest.

3Write the Test Application Class

Now we need a way to start the real application with that configuration added. SpringApplication.from() takes a reference to the application's normal main method and returns a builder; with() adds extra configuration classes to the context; run() starts it. Our production main method is reused exactly as it is.

Java
// src/test/java/com/acme/orders/TestOrdersApplication.java
public class TestOrdersApplication {
public static void main(String[] args) {
SpringApplication.from(OrdersApplication::main) // the real application
.with(ContainersConfig.class) // plus the container beans
.run(args);
}
}
// Log when run:
// Creating container for image: postgres:17
// Container postgres:17 started in PT2.1S
// HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@3c0a...
// Started TestOrdersApplication in 5.8 seconds
Step throughStarting the application with a Postgres container
TestOrdersApplicationSpring BootTestcontainersPostgres container
from(OrdersApplication::main).with(ContainersConfig)
start the postgres() bean
docker run postgres:17, wait until ready
@ServiceConnection: JdbcConnectionDetails
DataSource connects, migrations run
application started

6 messages in order. Play them, or step through them one at a time.

Because the class lives in src/test, its classpath includes the test dependencies, Testcontainers among them, while the main application never sees them. Flyway or Liquibase migrations run against the fresh container as usual, so the schema is created on start.

4Run It

We can run TestOrdersApplication's main method directly from the IDE. From the command line, the Spring Boot build plugins have a goal and a task made for this: they run the application using the test classpath and the test main class.

Java
# Maven
./mvnw spring-boot:test-run
# Gradle
./gradlew bootTestRun
# Then
curl localhost:8080/actuator/health
# {"status":"UP"}

The same ContainersConfig can be imported by integration tests with @Import(ContainersConfig.class) on a @SpringBootTest class, so development and tests share one definition of the database.

5Keep the Container Across DevTools Restarts

If DevTools is on the classpath, every code change restarts the application context. By default, closing the context also stops the container, so each restart would start a new, empty database, which costs a couple of seconds and loses any data we entered.

@RestartScope, an annotation from DevTools, fixes that. A bean in restart scope is created once and kept across DevTools restarts, so the same container, with its data, is reused by each new context.

Java
@Bean
@ServiceConnection
@RestartScope // from spring-boot-devtools
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>(DockerImageName.parse("postgres:17"));
}
// Before: restart -> new container, empty database, +2 s
// After: restart -> same container, data kept

For data that should outlive even the JVM, Testcontainers also has reusable containers with withReuse(true), which must be enabled on the developer's machine in its Testcontainers properties file; check the current documentation, as that feature is meant for local use only.

6Follow-up questions

Why put the test application in src/test instead of src/main?

Because Testcontainers and its configuration must never reach production. Classes and dependencies in src/test and test scope are not part of the packaged jar, so the production application keeps reading its real connection properties, and there is no risk of a container starting on a server.

How is this different from Docker Compose support?

Docker Compose support reads a compose.yaml and drives the docker compose command, which suits a long-lived environment shared with other tools. Testcontainers defines containers in Java and reuses the test configuration, so development and tests match exactly. Both create service connections, so the application code does not change.

Can we add more containers, such as Kafka or Redis?

Yes. We add another @Bean with @ServiceConnection for each one, for example a KafkaContainer or a generic container for Redis, and Boot creates the matching connection details. For a generic container, @ServiceConnection(name = "redis") tells Boot which kind of service it is.

7Conclusion

In this answer, we started an application locally with a PostgreSQL Testcontainer. A @TestConfiguration declares the container as a @Bean with @ServiceConnection, so Boot starts it and creates the connection details without properties. A TestOrdersApplication class in src/test calls SpringApplication.from(OrdersApplication::main).with(ContainersConfig.class).run(args), we run it with spring-boot:test-run or bootTestRun, and @RestartScope keeps the container alive across DevTools restarts.

What to say in the interviewAbout 70 seconds aloud

Open with

I would create two classes under src/test. The first is ContainersConfig, a @TestConfiguration with one @Bean method returning a PostgreSQLContainer for a pinned image like postgres:17, annotated with @ServiceConnection.

Then, if they want more

Spring Boot starts container beans itself and, because of @ServiceConnection, builds JdbcConnectionDetails from the container, so the DataSource connects without any spring.datasource properties. The second is TestOrdersApplication, with a main method that calls SpringApplication.from(OrdersApplication::main), then .with(ContainersConfig.class), then .run(args). That reuses the real main method and just adds the container configuration.

Since both classes live in src/test and the dependencies, spring-boot-testcontainers and the Testcontainers Postgres module, are test scoped, none of this reaches the production jar. To run it, I either start the class from the IDE or use mvn spring-boot:test-run or gradle bootTestRun.

If we use DevTools, I add @RestartScope to the container bean, so restarts after code changes reuse the same container and its data instead of starting a fresh one each time. And the integration tests can import the same ContainersConfig, so the local setup and the test setup are identical.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.1, Spring Boot 4
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to start an application locally with a Postgres Testcontainer instead of a...": https://scrivio-interview-library.netlify.app/spring-boot/developer-experience/46247b2819/