Categories
Docker Java SQL

Run PostgreSQL with Java and Testcontainers

In this tutorial, we will explain how to run PostgreSQL with Java and Testcontainers. Testcontainers is an awesome library that allows you to configure and start docker containers from Java.

To run a PostgreSQL database, you need Docker on your machine. Add these dependencies to your pom.xml:

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers</artifactId>
    <version>1.15.2</version>
</dependency>

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <version>1.15.2</version>
</dependency>

Then, simply run:

import org.testcontainers.containers.PostgreSQLContainer;

String databaseName = "database";
String username = "user";
String password = "password";

PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>("postgres:11.1").withDatabaseName(databaseName).withUsername(username).withPassword(password);
postgreSQLContainer.start();

Replace databaseName, username and password with your own values. Then, to get the url of the database, do:

String url = postgreSQLContainer.getJdbcUrl();

Finally, to stop the PostgreSQL database and the Docker container, do:

postgreSQLContainer.stop();

That’s it for this tutorial ! If you have any question, please leave a reply below, we answer within 24 hours.

Leave a Reply

Your email address will not be published. Required fields are marked *