Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Deployment and Coroutines

Configuration and Environments in Ktor

Configure a Ktor server for development, testing and production. Learn application.yaml, environment variable substitution, typed settings, secrets handling and failing fast on bad config.

The same Ktor application runs on your laptop, in a test, and in production, but each place needs different settings: a different port, a different database URL, a different JWT secret. The rule that makes this painless is the one from the twelve-factor approach: code stays the same, configuration comes from the environment. In this lesson you will see how Ktor reads configuration, how environment variables override file values, and how to turn raw strings into a typed, validated settings object that stops the server at startup if something is wrong.

Earlier you met the basics in Application Modules and Configuration. Here we go deeper into what you need to ship an app safely.

About the examples. Ktor is a Gradle dependency and cannot run in this page. The real application.yaml and Kotlin code are read-only. The runnable blocks are stand-ins: small plain-Kotlin programs that reproduce the same lookup rules so you can experiment with them.

application.yaml (or .conf)

Ktor 3 reads src/main/resources/application.yaml by default. HOCON (application.conf) works too and has the same structure. A typical file:

YAML
ktor:
  deployment:
    port: 8080
    host: 0.0.0.0
  application:
    modules:
      - com.example.ApplicationKt.module

app:
  name: "tasks-api"
  database:
    url: "jdbc:h2:mem:dev;DB_CLOSE_DELAY=-1"
    user: "sa"
    password: ""
  jwt:
    issuer: "https://tasks.example.com"
    secret: "dev-only-secret"

Everything under ktor: is read by Ktor itself (the port, the modules to start, timeouts, SSL). Everything under your own key (here app:) is yours. Keeping your settings under one prefix avoids clashes with Ktor's keys.

You read a value inside a module through environment.config:

Kotlin
fun Application.module() {
    val dbUrl = environment.config.property("app.database.url").getString()
    val port  = environment.config.propertyOrNull("app.metrics.port")?.getString()?.toInt() ?: 9090
}

property(...) throws if the key is missing, which is what you want for required settings. propertyOrNull(...) returns null for optional ones.

Environment variables override the file

You never want a production password in a file inside your Git repository. Ktor's config supports an environment placeholder syntax:

YAML
ktor:
  deployment:
    port: "$PORT:8080"
app:
  database:
    url: "$DATABASE_URL:jdbc:h2:mem:dev"
    password: "$DB_PASSWORD"
  jwt:
    secret: "$JWT_SECRET"

The form "$NAME:default" means: use the environment variable NAME, and if it is not set use the text after the colon. "$NAME" with no default means the variable is required; if it is missing, reading the property fails. In HOCON files the equivalent is port = ${?PORT}, which only overrides when the variable exists.

The program below is a runnable stand-in for this resolver. It takes a map of file values and a map of "environment variables" and applies the same rules.

Kotlin Stand-in: resolving $NAME:default placeholders

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.

On the laptop the defaults fill the gaps; in production the environment wins; with the secret forgotten the app refuses to start. That last behavior is deliberate and worth copying.

Pick the environment with a flag or a file

Many teams keep a small set of files: application.yaml (shared defaults), plus overrides per environment. Ktor lets you pass extra config files on the command line, and later files override earlier ones:

Terminal
java -jar app.jar -config=application.yaml -config=application-prod.yaml

Another common pattern is a single app.env value (dev, test, prod) that your module reads to switch behavior, for example to enable detailed error pages only in dev:

Kotlin
val env = environment.config.property("app.env").getString()
if (env == "dev") install(CallLogging) { level = Level.DEBUG }

Use this sparingly. If a module has many if (env == ...) branches, the code you test is no longer the code you run. Prefer different values over different code paths.

From strings to a typed settings object

Reading environment.config.property("a.b.c").getString() all over the app spreads magic strings everywhere. Instead, read the config once at startup into a data class and pass that around:

Kotlin
data class DbSettings(val url: String, val user: String, val password: String, val poolSize: Int)
data class JwtSettings(val issuer: String, val secret: String, val ttlMinutes: Long)
data class AppSettings(val db: DbSettings, val jwt: JwtSettings)

fun ApplicationConfig.toSettings() = AppSettings(
    db = DbSettings(
        url = property("app.database.url").getString(),
        user = property("app.database.user").getString(),
        password = property("app.database.password").getString(),
        poolSize = propertyOrNull("app.database.pool")?.getString()?.toInt() ?: 10,
    ),
    jwt = JwtSettings(
        issuer = property("app.jwt.issuer").getString(),
        secret = property("app.jwt.secret").getString(),
        ttlMinutes = propertyOrNull("app.jwt.ttl")?.getString()?.toLong() ?: 60,
    ),
)

Now every other function takes JwtSettings or DbSettings as a parameter. That is also what makes testing easy: a test builds a JwtSettings directly, without any file.

Fail fast: validate at startup

A wrong config discovered at 3 a.m. under load is far worse than a server that refuses to start. Validate in the settings class with require:

Kotlin
data class JwtSettings(val issuer: String, val secret: String, val ttlMinutes: Long) {
    init {
        require(secret.length >= 32) { "app.jwt.secret must be at least 32 characters" }
        require(ttlMinutes in 1..1440) { "app.jwt.ttl must be between 1 and 1440 minutes" }
    }
}

An exception in the module's startup code stops the application with a clear message. Orchestrators such as Docker or Kubernetes will then show a failed start instead of a running but broken server.

Kotlin Stand-in: a typed, validated settings object

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.

Notice the toString override: data classes print every field by default, so a casual log.info("settings: $settings") would write your secret into the logs. Mask sensitive fields.

Handling secrets

  • Never commit secrets. Keep application.yaml free of real passwords; use $VAR placeholders with no default for secrets.
  • Provide secrets through the platform: environment variables, Docker or Kubernetes secrets, or a secret manager that injects them at start.
  • Use different secrets per environment. A leaked development secret should never open production.
  • Add .env files to .gitignore if you use them locally.
  • Rotate secrets by design: for example, accept a list of JWT signing keys so a new key can be introduced before the old one is removed.

Config for tests

Tests can load a separate file (src/test/resources/application-test.yaml) or, better, build the config in code. With testApplication, you can set values explicitly and skip files entirely:

Kotlin
@Test
fun usesTestSettings() = testApplication {
    environment {
        config = MapApplicationConfig(
            "app.database.url" to "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
            "app.jwt.secret" to "test-secret-test-secret-test-secret",
        )
    }
    application { module() }
    // ...requests...
}

Common mistakes

  • Reading config values lazily inside handlers; a missing key then fails on the first request instead of at startup.
  • Defaults for secrets ("$JWT_SECRET:changeme"). The default will eventually reach production.
  • Logging whole settings objects.
  • Forgetting that environment variables are strings; parse and validate them (toInt(), ranges).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does "$PORT:8080" mean in application.yaml?

    The text after the colon is the default used when the environment variable is missing.
  2. 2. Why read configuration into a typed data class once at startup?

    A single typed object avoids magic strings, fails fast and can be built directly in tests.
  3. 3. Which is the safest way to handle a database password?

    A required placeholder keeps the secret out of the repository and stops startup when it is missing.
  4. 4. A settings data class prints all fields by default. What should you do for secrets?

    Masking prevents accidental secret leaks through logging.

Summary

  • Ktor reads application.yaml (or HOCON); your own settings live under your own key.
  • "$NAME:default" placeholders let the environment override file values; no default means required.
  • Parse config once into typed data classes and validate with require so bad config stops startup.
  • Keep secrets out of Git, use different values per environment, and never log them.
  • Prefer different values per environment over different code paths.

Next: Docker and Packaging