Ktor 2.3.4 Help

Configuration in code

Ktor allows you to configure various server parameters, such as a host address and port, modules to load, and so on. The configuration depends on the way you used to create a server - embeddedServer or EngineMain.

For embeddedServer, you can configure server parameters in code by passing the required parameters to the embeddedServer function. The embeddedServer function accepts different parameters for configuring a server, including a server engine, a host and port to listen, and so on. In this section, we'll take a look at several examples of running embeddedServer with different setting.

Basic configuration

The code snippet below shows the basic server setup with the Netty engine and the 8080 port.

import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { embeddedServer(Netty, port = 8080) { // ... }.start(wait = true) }

Note that you can set the port parameter to 0 to run the server on a random port. The embeddedServer function returns an engine instance, so you can get a port value in code using the ApplicationEngine.resolvedConnectors function.

Engine configuration

In the example below, we've added the configure parameter for configuring setting specific for a selected engine. You can learn more about configuring engines from Configure an engine.

import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { embeddedServer(Netty, port = 8080, configure = { connectionGroupSize = 2 workerGroupSize = 5 callGroupSize = 10 shutdownGracePeriod = 2000 shutdownTimeout = 3000 }) { // ... }.start(wait = true) }

Custom environment

The example below shows how to run a server with multiple connector endpoints using a custom environment represented by the ApplicationEngineEnvironment interface.

import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { val env = applicationEngineEnvironment { envConfig() } embeddedServer(Netty, env).start(true) } fun ApplicationEngineEnvironmentBuilder.envConfig() { module { module() } connector { host = "" port = 8080 } connector { host = "" port = 9090 } }

You can find the full example here: embedded-server-multiple-connectors.

Last modified: 14 December 2022