Language Support

› Java

› Deploying Spring Boot Applications to Heroku

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, safe-woodland-66362 https://safe-woodland-66362.herokuapp.com/ | https://git.heroku.com/safe-woodland-66362.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: ./mvnw -DskipTests clean dependency:list install ... remote: [INFO] BUILD SUCCESS remote: [INFO] ------------------------------------------------------------------------ remote: [INFO] Total time: 15.173 s remote: [INFO] Finished at: 2019-02-06T02:20:42Z remote: [INFO] ------------------------------------------------------------------------ remote: -----> Discovering process types remote: Procfile declares types -> (none) remote: Default types for buildpack -> web remote: remote: -----> Compressing... remote: Done: 64.8M remote: -----> Launching... remote: Released v3 remote: https://safe-woodland-66362.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/safe-woodland-66362.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 2019-02-06T02:20:58.271708+00:00 app[web.1]: Picked up JAVA_TOOL_OPTIONS: -Xmx300m -Xss512k -XX:CICompilerCount=2 -Dfile.encoding=UTF-8 2019-02-06T02:20:54.000000+00:00 app[api]: Build succeeded 2019-02-06T02:21:04.504651+00:00 app[web.1]: 2019-02-06 02:21:04.503 INFO 4 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 57733 (http) 2019-02-06T02:21:04.609263+00:00 app[web.1]: 2019-02-06 02:21:04.608 INFO 4 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-02-06T02:21:04.609630+00:00 app[web.1]: 2019-02-06 02:21:04.609 INFO 4 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.14] 2019-02-06T02:21:04.660219+00:00 app[web.1]: 2019-02-06 02:21:04.659 INFO 4 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/app/.jdk/jre/lib/amd64/server::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib] 2019-02-06T02:21:04.869403+00:00 app[web.1]: 2019-02-06 02:21:04.869 INFO 4 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-02-06T02:21:04.869559+00:00 app[web.1]: 2019-02-06 02:21:04.869 INFO 4 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3453 ms 2019-02-06T02:21:05.613519+00:00 app[web.1]: 2019-02-06 02:21:05.613 INFO 4 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-02-06T02:21:06.229996+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 === safe-woodland-66362 Config Vars DATABASE_URL: postgres://evxybkkmiodzdd:857fa7799badf797bc9ae444b67dab94d2490e4a25d5a2d112019fbc75b8c42e@ec2-54-225-237-84.compute-1.amazonaws.com:5432/d3ftstv7m1o4k2

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: 10.6 Created: 2019-02-06 02:21 UTC Data Size: 7.6 MB Tables: 0 Rows: 0/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-clean-86646

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 .

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.