Ktor 3.0.0-beta-2 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 configuration represented by the ApplicationEngine 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 appProperties = applicationProperties { module { module() } } embeddedServer(Netty, appProperties) { envConfig() }.start(true) } fun ApplicationEngine.Configuration.envConfig() { connector { host = "0.0.0.0" port = 8080 } connector { host = "127.0.0.1" port = 9090 } }

For the complete example, see embedded-server-multiple-connectors.

Last modified: 30 April 2024