Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 38 ยท Getting Started

Application Modules and Configuration

Configure a Ktor server with application.conf or YAML: ports, modules, environment variables, custom settings, and reading config values safely in code.

A real server needs settings that change between your laptop, the test run and production: the port, database URL, secrets, feature flags. Ktor handles this with a configuration file that lives in src/main/resources, plus modules, the functions that wire your application together. This lesson shows both, with environment-variable overrides, custom settings, and a runnable stand-in for the configuration lookup.

Modules

A module is any function that takes an Application as its receiver (or parameter) and configures it. You can have as many as you like:

Kotlin
fun Application.module() {
    configureSerialization()
    configureRouting()
}

fun Application.adminModule() {
    routing {
        get("/admin/ping") { call.respondText("pong") }
    }
}

With EngineMain, you list the modules to load by their fully qualified name in the config file (shown below). They run in the order listed. Splitting an application into modules is useful when parts are independent, for example apiModule, adminModule and metricsModule.

application.conf (HOCON)

The classic format is HOCON, a relaxed superset of JSON:

TEXT
ktor {
    deployment {
        port = 8080
        port = ${?PORT}
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
}

app {
    name = "My Service"
    database {
        url = "jdbc:h2:mem:dev"
        url = ${?DATABASE_URL}
        poolSize = 5
    }
    jwt {
        secret = "dev-only-secret"
        secret = ${?JWT_SECRET}
    }
}

Notes:

  • port = ${?PORT} means: if the environment variable PORT exists, use it; otherwise keep the earlier value. This is the standard way to make a setting overridable in production without changing the file.
  • modules is a list of package.FileNameKt.functionName. The file Application.kt compiles to the class ApplicationKt.
  • Anything outside ktor { } is yours: Ktor does not interpret the app { } block.

application.yaml

Since Ktor 3 you can use YAML instead (a file named application.yaml). It needs the ktor-server-config-yaml dependency, and environment variables use the $NAME:default syntax:

TEXT
ktor:
    deployment:
        port: "$PORT:8080"
    application:
        modules:
            - com.example.ApplicationKt.module
app:
    name: "My Service"

Pick one format and keep to it. The rest of this course uses HOCON.

Reading settings in code

Inside a module you can read any value through environment.config:

Kotlin
fun Application.module() {
    val appName = environment.config.property("app.name").getString()
    val poolSize = environment.config.property("app.database.poolSize").getString().toInt()
    val optional = environment.config.propertyOrNull("app.feature.beta")?.getString()

    log.info("Starting $appName with pool size $poolSize")
}

property(...) throws a clear ApplicationConfigurationException if the key is missing, which is exactly what you want for required settings: the application refuses to start with a message naming the key, rather than failing later with a NullPointerException. propertyOrNull is for optional values.

For many settings, copy them once into a typed class:

Kotlin
data class DbConfig(val url: String, val poolSize: Int)

fun ApplicationConfig.dbConfig() = DbConfig(
    url = property("app.database.url").getString(),
    poolSize = property("app.database.poolSize").getString().toInt(),
)

Overriding with command-line arguments

EngineMain also accepts -P:key=value arguments, which beat the config file:

TEXT
java -jar app.jar -P:ktor.deployment.port=9090 -P:app.name="Staging"

So the order of precedence is: command-line -P: arguments, then environment variables substituted by ${?VAR}, then the file's own values.

Separate test configuration

When you run tests, you can use a different file. Put application-test.conf in src/test/resources and load it in the test:

Kotlin
testApplication {
    environment {
        config = ApplicationConfig("application-test.conf")
    }
    // ...
}

Tests can then use an in-memory database and a throw-away secret without touching production settings. The testing chapter of this track covers testApplication in depth.

Stand-in: layered config with environment overrides

The program below is a stand-in. It does not parse HOCON, but it reproduces the lookup rules: a file of dotted keys, overridden by environment variables (passed in as a map so the output is deterministic), then by command-line style overrides. It also shows the fail-fast required-key behaviour.

Kotlin Stand-in: layered configuration lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The two calls to remember: property for required values (fail fast) and propertyOrNull for optional ones.

Never commit real secrets such as a production JWT key or database password to application.conf. Keep only development defaults in the file and read production secrets from environment variables (secret = ${?JWT_SECRET}) or a secrets manager.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does port = ${?PORT} do in a HOCON file?

    The question mark makes the substitution optional: the earlier value stays when PORT is not set.
  2. 2. Which call should you use for a setting the application cannot start without?

    property throws a clear configuration error at startup when the key is missing.
  3. 3. How are the modules loaded by EngineMain declared?

    The modules list in application.conf names each module function.
  4. 4. Which source wins when the same key is set in several places?

    Command-line arguments have the highest precedence, then substituted environment variables, then file values.

Summary

  • A module is a function on Application; EngineMain loads those named in ktor.application.modules.
  • application.conf (HOCON) or application.yaml holds ports and your own settings.
  • ${?VAR} makes a setting overridable by an environment variable.
  • Read settings with environment.config.property(...) (required) or propertyOrNull(...) (optional).
  • Keep secrets out of the file; use a test config for tests.

Next: How Ktor Handles a Request