Setting Environment Variable

In this post under TestContainer, I will explain with example how to set environment variable before starting a container.

For our example, we will use the latest “postgres” image from Docker Hub.

According to “postgres” help page on Docker Hub we only need to set the environment variable “POSTGRES_PASSWORD” to start the postgres container and login into it.

Below is the complete code that shows how to set the environment variable, start the container and get a jdbc connection object to postgres db.

Main Class

1  package package4;
3  import java.sql.Connection;
4  import java.sql.DriverManager;
5  import java.sql.SQLException;
7  import org.testcontainers.containers.GenericContainer;
8  import org.testcontainers.utility.DockerImageName;
10 public class Example4 {
11     public static void main(String[] args) {
12         DockerImageName dockerImageName = DockerImageName.parse("postgres:latest");
13         try (GenericContainer<?> container = new GenericContainer<>(dockerImageName).withExposedPorts(5432)) {
14             container.addEnv("POSTGRES_PASSWORD", "postgres");
15             container.start();
16             System.out.println(container.getMappedPort(5432));
17             try(Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:" + container.getMappedPort(5432) + "/postgres", "postgres", "postgres")) {
18                 System.out.println("Connection Successful");
19             } catch (SQLException sqlException) {
20                 System.out.println("Connection Failed");
21                 sqlException.printStackTrace();
22             }
23             System.out.println("Done");
24         }
25     }
26 }

In the above code, at line 12, we create “DockerImageName” class instance of name “dockerImageName” by calling static “parse” method and passing image name as an argument.

At line 13, we create an instance of “GenericContainer” class using the “dockerImageName” instance and expose “5432” port.

At line 14, we set the environment variable “POSTGRES_PASSWORD” by calling “addEnv” method on the container instance. To this method we pass the environment variable name and value.

So in this case the environment variable name is “POSTGRES_PASSWORD” and the value is “postgres”.

At line 17, we try to connect to postgres db using the mapped port of “5432”, username and password.

In this way we can set an environment variable before starting the container.

Leave a Reply