Search

Dark theme | Light theme

October 2, 2015

Ratpacked: Change Server Port With Environment Variable

When we define a Ratpack application we can set a server port in the server configuration code. When we do not define the port number in our code and use the default server configuration we can also set the server port with the environment variables PORT or RATPACK_PORT.

In the following example we use Gradle as build tool to run our Ratpack application. Gradle will pass on environment variables to the run task. We use the environment variable RATPACK_PORT to change the port to 9000:

$ RATPACK_PORT=9000 gradle run
Starting server...
Building registry...
Ratpack started (development) for http://localhost:9000

Alternatively we can define the port number in our configuration, but also add an option to support environment variables to set or override configuration properties. This support is simply added by invoking the env method on the ConfigDataBuilder interface. With this method Ratpack looks for environment variables that start with RATPACK_. The rest of the environment variable is then parsed and transformed to a configuration property. A double underscore is used as separator between sections, a single underscore is used as boundary for camel case fields. For example the environment variable RATPACK_SERVER__PORT transforms to server.port.

import static ratpack.groovy.Groovy.ratpack

ratpack {
    serverConfig {
        // Instruct Ratpack to look for
        // environment variables that
        // start with RATPACK_ as
        // configuration properties.
        env()
    }
}

Let's run our application and use the environment variable RATPACK_SERVER__PORT to change the port number:

$ RATPACK_SERVER__PORT=9000 gradle run
Starting server...
Building registry...
Ratpack started (development) for http://localhost:9000

We can alter the default prefix RATPACK for environment variables. We still use the method env, but this time we specify an argument as the prefix for the environment variables. In the following code we see how to use the prefix COCKTAILS_ for environment variables:

package learning.ratpack;

import ratpack.server.RatpackServer;

public class Main {
    public static void main(String[] args) throws Exception {
        RatpackServer.start(server ->
            server
                .serverConfig(serverConfig ->
                    serverConfig
                        // Define prefix for environment
                        // variables that Ratpack uses.
                        .env("COCKTAILS_")));
    }
}

Let's run our application and use the environment variable COCKTAILS_SERVER__PORT to change the port number:

$ COCKTAILS_SERVER__PORT=9000 gradle run
Starting server...
Building registry...
Ratpack started (development) for http://localhost:9000

Written with Ratpack 1.0.0.