Deploying Spring Boot Applications to Heroku

The Spring Boot model of deploying standalone applications is a great fit for Heroku. You can use either Maven or Gradle to deploy a Spring application on Heroku, but for this guide we’ll assume that you’re using Maven and have Maven 3 installed on your machine.

To begin, create a free Heroku account. Then download and install the Heroku CLI.

Download the Heroku CLI

Once installed, you can use the heroku command from the terminal to log in using the email address and password you used when creating your Heroku account:

$ heroku login heroku: Press any key to open up the browser to login or q to exit › Warning: If browser does not open, visit › https://cli-auth.heroku.com/auth/browser/*** heroku: Waiting for login... Logging in... done Logged in as me@example.com

To check that your key was added, run heroku keys . If your key isn’t there, you can add it manually by running heroku keys:add . For more information about SSH keys, see Managing Your SSH Keys.

Creating a Spring Boot app

To create a new Spring Boot application, first install the Spring Boot CLI as described in the Spring Boot documentation. This will add a spring command to your path.

You can also start with a working sample app if you’d prefer.

Use the CLI to create a new application by running this command:

$ spring init --dependencies=web demo

Then move into the application directory:

$ cd demo

The application does not have any custom logic by default – it’s just an empty template. To add some behavior, open the src/main/java/com/example/demo/DemoApplication.java file and put the following code in it:

In file src/main/java/com/example/demo/DemoApplication.java write:

package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.*; import org.springframework.stereotype.*; @Controller @SpringBootApplication public class DemoApplication { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

This creates a simple request mapping that displayed “Hello World!” in the browser. You could run the application locally to confirm this, but we’ll jump straight to running it on Heroku.

Preparing a Spring Boot app for Heroku

Before you can deploy the app to Heroku, you’ll need to create a Git repository for the application and add all of the code to it by running these commands:

$ git init $ git add . $ git commit -m "first commit"

You’ll deploy the app by pushing this Git repo to Heroku. It’s also possible to deploy using the Heroku Maven plugin, but this guide will focus on using Git and the Heroku CLI.

In order to deploy to Heroku, you’ll first need to provision a new Heroku app. Run this command:

$ heroku create Creating app... done, tranquil-mountain-19785 https://tranquil-mountain-19785.herokuapp.com/ | https://git.heroku.com/tranquil-mountain-19785.git

This also creates a remote repository called heroku in your local git repo. Heroku generates a random name (in this case nameless-lake-8055 ) for your app. You can rename it later with the heroku apps:rename command.

Now deploy your code:

$ git push heroku master remote: Compressing source files... done. remote: Building source: remote: remote: -----> Java app detected remote: -----> Installing JDK 1.8... done remote: -----> Executing Maven ... remote: [INFO] BUILD SUCCESS remote: [INFO] ------------------------------------------------------------------------ remote: [INFO] Total time: 15.129 s remote: [INFO] Finished at: 2020-05-20T09:17:47Z remote: [INFO] ------------------------------------------------------------------------ remote: -----> Discovering process types remote: Procfile declares types -> (none) remote: Default types for buildpack -> web remote: remote: -----> Compressing... remote: Done: 65M remote: -----> Launching... remote: Released v3 remote: https://tranquil-mountain-19785.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/tranquil-mountain-19785.git * [new branch] master -> master

Heroku automatically detects the application as a Maven/Java app due to the presence of a pom.xml file. It installed Java 8 by default, but you can easily configure this with a system.properties file as described in the Specifying a Java version Dev Center article. It will run your app using the default command.

All that said, the application is now deployed. You can visit the app’s URL by running this command:

$ heroku open

You’ll see the “Hello World!” text in the browser.

You can view the logs for the application by running this command:

$ heroku logs --tail 2020-05-20T09:18:00.899237+00:00 app[web.1]: 2020-05-20 09:18:00.899 INFO 4 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default 2020-05-20T09:18:02.348822+00:00 app[web.1]: 2020-05-20 09:18:02.348 INFO 4 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 40371 (http) 2020-05-20T09:18:02.365045+00:00 app[web.1]: 2020-05-20 09:18:02.364 INFO 4 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2020-05-20T09:18:02.365316+00:00 app[web.1]: 2020-05-20 09:18:02.365 INFO 4 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.35] 2020-05-20T09:18:02.457002+00:00 app[web.1]: 2020-05-20 09:18:02.456 INFO 4 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2020-05-20T09:18:02.457162+00:00 app[web.1]: 2020-05-20 09:18:02.457 INFO 4 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1486 ms 2020-05-20T09:18:02.692238+00:00 app[web.1]: 2020-05-20 09:18:02.691 INFO 4 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2020-05-20T09:18:02.891409+00:00 app[web.1]: 2020-05-20 09:18:02.891 INFO 4 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 40371 (http) with context path '' 2020-05-20T09:18:02.903573+00:00 app[web.1]: 2020-05-20 09:18:02.903 INFO 4 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 2.739 seconds (JVM running for 3.302) 2020-05-20T09:18:03.300746+00:00 heroku[web.1]: State changed from starting to up

Reload your application in the browser, and you’ll see another log message generated for that request. Press Control+C to stop streaming the logs.

To learn more about the basics of deploying a Maven-based Java application on Heroku, try following the Getting Started with Java on Heroku guide. This guide covers many steps that are not specific to Spring Boot.

The remainder of this article provides a cursory overview of some of the most common settings you’ll need to adjust.

Connecting to a database

You can attach a PostgreSQL database to your app by running the following command from the CLI:

$ heroku addons:create heroku-postgresql

If you prefer to use MySQL or another database vendor, check out Add-ons Marketplace to see what is available.

Now you can list the configuration variables for your app to display the URL needed to connect to the database, DATABASE_URL:

$ heroku config === tranquil-mountain-19785 Config Vars DATABASE_URL: postgres://fhehmrcgzmpjhn:30af34cb97bae5f97d6c6a13ceb6a74d6511d6f16ec77bdaadab09a398857784@ec2-35-169-254-43.compute-1.amazonaws.com:5432/defp5q4qsijggp

Heroku also provides a pg command that shows a lot more:

$ heroku pg === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 12.2 Created: 2020-05-20 09:18 UTC Data Size: 7.9 MB Tables: 0 Rows: 0/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-animated-55555

This indicates a hobby database (free) is running Postgres 9.3.3, with a single row of data.

Once the database add-on has been created, Heroku will automatically populate the environment variables SPRING_DATASOURCE_URL , SPRING_DATASOURCE_USERNAME , and SPRING_DATASOURCE_PASSWORD . These environment variables should allow your Spring Boot application to connect to the database without any other configuration as long as you add a PostgreSQL JDBC driver to your dependencies like so:

In file pom.xml , on line 26 add:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency>

You can customize your application’s database configuration in your application.properties . For example:

In file src/main/resources/application.properties write:

spring.datasource.driverClassName=org.postgresql.Driver spring.datasource.maxActive=10 spring.datasource.maxIdle=5 spring.datasource.minIdle=2 spring.datasource.initialSize=5 spring.datasource.removeAbandoned=true

Then you can then add a configuration bean to your app.

In file src/main/java/demo/DatabaseConfig.java write:

package com.example.demo; import com.zaxxer.hikari.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import javax.sql.DataSource; @Configuration public class DatabaseConfig { @Value("${spring.datasource.url}") private String dbUrl; @Bean public DataSource dataSource() { HikariConfig config = new HikariConfig(); config.setJdbcUrl(dbUrl); return new HikariDataSource(config); } }

For more information, see Connecting to Relational Databases on Heroku with Java.

Now your application should be able to connect to the database. You can follow our guide on Running Database Migrations for Java Apps to initialize the database. The sample app uses Liquibase.

Customizing the boot command

You can override the default command used to run your app or define custom process types using a Procfile . The correct command depends on what you need to do with your app. Common process types are used to run a web process or run database migrations.

Next steps

For more complete examples of Spring Boot apps that run on Heroku see:

Heroku provides a wide range of features for Spring applications. You can provision add-ons that introduce third-party cloud services like persistence, logging, monitoring and more. The add-on marketplace has a large number of data stores, from Redis and MongoDB providers, to Postgres and MySQL.

You can read more about How Heroku Works to get a technical overview of the concepts you’ll encounter while writing, configuring, deploying and running applications. Then visit the Java category on Dev Center to learn more about developing and deploying Spring applications. If you experience any trouble with your application as you migrate to Heroku, reach out to any of our Support channels.

For more information on deploying Spring apps, see the Spring documentation and the Spring Boot documentation on deploy to Heroku.