Creating a server
Before creating a Ktor application, you need to take into account how your application will be deployed:
In this case, an application engine used to process network requests should be a part of your application. Your application has control over engine settings, connection, and SSL options.
As a servlet
In this case, a Ktor application can be deployed inside a servlet container (such as Tomcat or Jetty), which controls the application lifecycle and connection settings.
Self-contained package
To deliver a Ktor server application as a self-contained package, you need to create a server first. Server configuration can include different settings: a server engine (such as Netty, Jetty, etc.), various engine-specific options, host and port values, and so on. There are two main approaches in Ktor for creating and running a server:
The
embeddedServerfunction is a simple way to configure server parameters in code and quickly run an application.EngineMainprovides more flexibility to configure a server. You can specify server parameters in a file and change a configuration without recompiling your application. Moreover, you can run your application from a command line and override the required server parameters by passing corresponding command-line arguments.
Configuration in code
The embeddedServer function is a simple way to configure server parameters in code and quickly run an application. In the code snippet below, it accepts an engine and port as parameters to start a server. In the example below, we run a server with the Netty engine and listen on the 8080 port:
For the full example, see embedded-server.
Configuration in a file
EngineMain starts a server with the selected engine and loads application modules from an external configuration file – either application.conf or application.yaml, typically located in the resource directory.
In addition to specifying which modules to load, the configuration file can include various server parameters such as the port, host, and SSL settings. For example, the configuration below sets the server port to 8080.
For the full examples, see engine-main and engine-main-yaml.
Servlet
A Ktor application can be run and deployed inside servlet containers that include Tomcat and Jetty. To deploy inside a servlet container, you need to generate a WAR archive and then deploy it to a server or a cloud service that supports WARs.