Heroku
In this tutorial, we'll show you how to prepare and deploy a Ktor application to Heroku.
Prerequisites
Before starting this tutorial, make sure that the following prerequisites are met:
You have a Heroku account.
Heroku CLI is installed on your machine.
Create a sample application
Create a sample application as described in Create, open and run a new Ktor project.
Prepare an application
Step 1: Configure a port
First, you need to specify a port used to listen for incoming requests. Since Heroku uses the PORT
environment variable, you need to configure the application to use a value of this variable. Depending on the way used to configure a Ktor server, do one of the following:
If server configuration is specified in code, you can obtain the environment variable value using
System.getenv
. Open theApplication.kt
file placed in thesrc/main/kotlin/com/example
folder and change theport
parameter value of theembeddedServer
function as shown below:fun main() { embeddedServer(Netty, port = System.getenv("PORT").toInt()) { // ... }.start(wait = true) }If your server configuration is specified in the
application.conf
file, you can assign the environment variable to theport
parameter by using the${ENV}
syntax. Open theapplication.conf
file placed insrc/main/resources
and update it as shown below:ktor { deployment { port = 8080 port = ${?PORT} } }
Step 2: Add a stage task
Open the build.gradle.kts
file and add a custom stage
task used by Heroku to make an executable that gets run on Heroku's platform:
Note that the installDist
task comes with the Gradle application plugin, which is already added to the sample project.
Step 3: Create a Procfile
Create a Procfile in a project root and add the following content:
This file specifies a path to the application's executable generated by the stage task and allows Heroku to start the application. You might need to replace ktor-get-started-sample
with you project name.
Deploy an application
To deploy the application to Heroku using Git, open the terminal and follow the steps below:
Commit changes made in the previous section locally:
git add . git commit -m "Prepare app for deploying"Login to Heroku CLI:
heroku loginCreate a Heroku application using the
heroku create
command. You need to replacektor-sample-heroku
with a name of your application:heroku create ktor-sample-herokuThis command does two things:
Creates a new Heroku application, which is available on the web dashboard.
Adds a new Git remote called
heroku
to a local repository.
To deploy the application, push changes to
heroku main
...git push heroku main... and wait until Heroku builds and publishes the application:
... remote: https://ktor-sample-heroku.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done.