Environment variables

Environment variables keep your app secure, flexible and organized. Let’s take a look at how to pass enviroment variables to containers.

Using an environment variable with your container

Let’s edit the Java application you created using Quarkus:

code .

Now edit the HelloResource.java class like this:

package com.redhat.developers;

import java.util.Optional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.config.inject.ConfigProperty;

@Path("/hello")
public class HelloResource {

    @ConfigProperty(name = "config")
    Optional<String> config;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return config.orElse("no config");
    }
}

Notice that instead of just printing hello, it will print the content of a ConfigProperty or print no config if the config doesn’t exist.

Now, back to terminal, package your project:

mvn package -DskipTests=true

Rebuild our image to get the new version of the application:

docker build -t my-image .

Remove your running container:

docker rm -f my-container

And run the new one:

docker run -d --name my-container -p 8080:8080 my-image

Now let’s call the application:

curl localhost:8080/hello

You now got this output.

no config

The no config output happens because we didn’t really create the environment variable. Let’s fix it.

Edit your Dockerfile like this:

FROM registry.access.redhat.com/ubi8/openjdk-17

COPY target/quarkus-app/lib/ /deployments/lib/
COPY target/quarkus-app/*.jar /deployments/app.jar
COPY target/quarkus-app/app/ /deployments/app/
COPY target/quarkus-app/quarkus/ /deployments/quarkus/

ENV config=dockerfile

CMD ["java", "-jar", "/deployments/app.jar"]

Let’s rebuild our image, re-create the container and call it again:

docker build -t my-image .
docker rm -f my-container
docker run -d --name my-container -p 8080:8080 my-image
curl localhost:8080/hello

Now your output is:

dockerfile

Finally, let’s replace the variable’s content. First we remove the container:

docker rm -f my-container

And then we re-create it passing a new value for the environment variable:

docker run -d --name my-container -p 8080:8080 -e config=container my-image

Then we call the application again:

curl localhost:8080/hello

And the output is:

container