Getting Started on Heroku with Java
Introduction
This tutorial will have you deploying a Java app in minutes.
Hang on for a few more minutes to learn how it all works, so you can make the most out of Heroku.
The tutorial assumes that you already have:
- A free Heroku account
- Java 8 installed
- Maven 3 installed
If you’d prefer to use Gradle instead of Maven, please see the Getting Started with Gradle on Heroku guide.
Set up
The Heroku CLI requires Git, the popular version control system. If you don’t already have Git installed, complete the following before proceeding:
In this step you’ll install the Heroku Command Line Interface (CLI). You use the CLI to manage and scale your applications, provision add-ons, view your application logs, and run your application locally.
Download and run the installer for your platform:
Download the appropriate installer for your Windows installation:
Run the following from your terminal:
$ sudo snap install heroku --classic
When installation completes, you can use the heroku
command from your terminal.
Use the heroku login
command to log in to the Heroku CLI:
$ 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
This command opens your web browser to the Heroku login page. If your browser is already logged in to Heroku, simply click the Log in button displayed on the page.
This authentication is required for both the heroku
and git
commands to work correctly.
Note that if you’re behind a firewall that requires use of a proxy to connect with external HTTP/HTTPS services, you can set the HTTP_PROXY
or HTTPS_PROXY
environment variables in your local development environment before running the heroku
command.
Prepare the app
In this step, you will prepare a sample application that’s ready to be deployed to Heroku.
If you are new to Heroku, it is recommended that you complete this tutorial using the Heroku-provided sample application.
However, if you have your own existing application that you want to deploy instead, see this article to learn how to prepare it for Heroku deployment.
To create a local copy of a sample app that you can deploy to Heroku, execute the following commands in your local command shell or terminal:
$ git clone https://github.com/heroku/java-getting-started
$ cd java-getting-started
You now have a functioning Git repository that contains a simple Java application. The application includes a pom.xml
file, which is used by Java’s dependency manager, Maven.
Deploy the app
In this step you’ll deploy the sample app to Heroku.
First, create an app on Heroku, which prepares Heroku to receive your source code:
$ heroku create
Creating app... done, stark-earth-43785
https://stark-earth-43785.herokuapp.com/ | https://git.heroku.com/stark-earth-43785.git
When you create an app, a Git remote (named heroku
) is also created and associated with your local Git repository.
By default, Heroku generates a random name for your app. You can pass a parameter to specify your own app name.
Now deploy your code:
$ git push heroku main
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Java app detected
remote: -----> Installing JDK 1.8... done
remote: -----> Executing Maven
...
remote: [INFO] ------------------------------------------------------------------------
remote: [INFO] BUILD SUCCESS
remote: [INFO] ------------------------------------------------------------------------
remote: [INFO] Total time: 16.233 s
remote: [INFO] Finished at: 2020-09-03T19:53:21Z
remote: [INFO] ------------------------------------------------------------------------
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 71.4M
remote: -----> Launching...
remote: Released v5
remote: https://stark-earth-43785.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/stark-earth-43785.git
* [new branch] main -> main
The application is now deployed. Ensure that at least one instance of the app is running:
$ heroku ps:scale web=1
Now visit the app at the URL generated by its app name. As a handy shortcut, you can open the website like so:
$ heroku open
View logs
Heroku aggregates all of the output streams from both your app and the platform’s components into a single channel of time-ordered logs.
View information about your running app using the heroku logs --tail
command:
$ heroku logs --tail
2020-09-03T19:53:41.834061+00:00 app[web.1]: 2020-09-03 19:53:41.833 INFO 4 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9160 (http) with context path ''
2020-09-03T19:53:41.859513+00:00 app[web.1]: 2020-09-03 19:53:41.859 INFO 4 --- [ main] com.example.Main : Started Main in 5.223 seconds (JVM running for 6.015)
2020-09-03T19:53:42.284354+00:00 heroku[web.1]: State changed from starting to up
2020-09-03T19:53:45.480254+00:00 app[web.1]: 2020-09-03 19:53:45.479 INFO 4 --- [nio-9160-exec-3] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-09-03T19:53:45.480412+00:00 app[web.1]: 2020-09-03 19:53:45.480 INFO 4 --- [nio-9160-exec-3] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-09-03T19:53:45.490317+00:00 app[web.1]: 2020-09-03 19:53:45.490 INFO 4 --- [nio-9160-exec-3] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms
2020-09-03T19:53:46.177377+00:00 heroku[router]: at=info method=GET path="/" host=stark-earth-43785.herokuapp.com request_id=16e66b60-d846-404a-a8b8-c46689071573 fwd="13.110.54.39" dyno=web.1 connect=0ms service=734ms status=200 bytes=7330 protocol=https
2020-09-03T19:53:46.374506+00:00 heroku[router]: at=info method=GET path="/stylesheets/main.css" host=stark-earth-43785.herokuapp.com request_id=aadacd54-0b4b-442e-8857-1382390cb443 fwd="13.110.54.39" dyno=web.1 connect=0ms service=22ms status=200 bytes=896 protocol=https
2020-09-03T19:53:46.472719+00:00 heroku[router]: at=info method=GET path="/lang-logo.png" host=stark-earth-43785.herokuapp.com request_id=a362c2c2-6bf5-49ba-9d48-a49c8f100b8d fwd="13.110.54.39" dyno=web.1 connect=0ms service=6ms status=200 bytes=4433 protocol=https
2020-09-03T19:53:46.551719+00:00 heroku[router]: at=info method=GET path="/webjars/jquery/3.3.1-1/jquery.min.js" host=stark-earth-43785.herokuapp.com request_id=99a7f95a-5067-4315-842f-5b4116d715ba fwd="13.110.54.39" dyno=web.1 connect=1ms service=8ms status=200 bytes=87218 protocol=https
Visit your application in the browser again to generate another log message.
Press CTRL+C
to stop streaming logs.
Define a Procfile
Heroku apps use a special plaintext file called the Procfile to explicitly declare what command should be executed to start your app.
The Procfile
in the example app you deployed looks like this:
web: java -jar target/java-getting-started-1.0.jar
This declares a single process type, web
, and the command needed to run it. The name web
is important here. It declares that this process type will be attached to Heroku’s HTTP routing stack, and it will be able to receive web traffic.
Procfiles can contain additional process types. For example, you might declare one for a background worker that processes items off of a queue.
Scale the app
Right now, your app is running on a single web dyno. A dyno is a lightweight Linux container that runs the command specified in your Procfile
.
You can check how many dynos are running using the heroku ps
command:
$ heroku ps
Free dyno hours quota remaining this month: 999h 46m (99%)
Free dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/dyno-sleeping
=== web (Free): java -jar target/java-getting-started-1.0.jar (1)
web.1: up 2020/09/03 14:53:42 -0500 (~ 11s ago)
By default, your app is deployed on a free dyno. Free dynos sleep after thirty minutes of inactivity (i.e., if they don’t receive any traffic). This causes a delay of a few seconds for the first request upon waking. Subsequent requests will perform normally.
Free dynos consume from a monthly, account-level quota of free dyno hours. As long as the quota is not exhausted, your free apps can continue to run.
To avoid dyno sleeping, you can upgrade to a hobby or professional dyno type as described in Dyno Types. For example, if you migrate your app to a professional dyno, you can easily scale it by running a command telling Heroku to spin up a specific number of dynos, each running your web process type.
Scaling an application on Heroku is equivalent to changing the number of dynos that are running.
Scale the number of web dynos to zero:
$ heroku ps:scale web=0
Access the app again by refreshing your browser or running heroku open
. You will get an error message because your app no longer has any web dynos available to serve requests.
Scale it up again:
$ heroku ps:scale web=1
To prevent abuse, scaling a non-free application to more than one dyno requires account verification.
Declare app dependencies
Heroku automatically identifies an app as a Java app if it contains a pom.xml
file in the root directory. You can create a pom.xml
file for your own apps with the mvn archetype:create
command.
The demo app you deployed already has a pom.xml
(see it here). Here’s an excerpt:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The pom.xml
file specifies dependencies that should be installed with your application. When an app is deployed, Heroku reads this file and installs the dependencies by running mvn clean install
.
Another file, system.properties
, indicates the version of Java to use (Heroku supports many different versions). The contents of this optional file are straightforward:
java.runtime.version=1.8
Run mvn clean install
in your local directory to install the dependencies, preparing your system for running the app locally. Note that this app requires Java 8, but you can push your own apps using a different version of Java.
$ mvn clean install
...
[INFO] Installing /Users/rschneeman/Documents/projects/tmp/java-getting-started/docs/tmp/java-getting-started/pom.xml to /Users/rschneeman/.m2/repository/com/example/java-getting-started/1.0/java-getting-started-1.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 48.930 s
[INFO] Finished at: 2020-09-03T14:54:50-05:00
[INFO] ------------------------------------------------------------------------
If you do not have Maven installed, or get an error like 'mvn' is not recognized as an internal or external command
, then you can use the wrapper command instead by running mvnw clean install
on Windows or ./mvnw clean install
on Mac and Linux. This both installs Maven and runs the Maven command.
The Maven process compiles and build a JAR, with dependencies, placing it into your application’s target
directory. This process is accomplished with the spring-boot-maven-plugin
in the pom.xml
.
If you aren’t using Spring in your app, you can accomplish this with the following plugin configuration in the pom.xml
file.
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>helloworld</finalName>
</configuration>
</plugin>
Once dependencies are installed, you can run your app locally.
Run the app locally
Start your application locally with the heroku local
CLI command (make sure you’ve already run mvn clean install
):
$ heroku local web
...
2:55:00 PM web.1 | 2020-09-03 14:55:00.302 INFO 24498 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2:55:00 PM web.1 | 2020-09-03 14:55:00.478 INFO 24498 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2:55:01 PM web.1 | 2020-09-03 14:55:01.000 INFO 24498 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2:55:01 PM web.1 | 2020-09-03 14:55:01.059 INFO 24498 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 5000 (http) with context path ''
Just like the Heroku platform, heroku local
examines your Procfile
to determine what command to run.
Open http://localhost:5000 with your web browser. You should see your app running locally.
To stop the app from running locally, go back to your terminal window and press CTRL+C
to exit.
Push local changes
In this step you’ll learn how to make local changes to your app and deploy them to Heroku. As an example, you’ll add a dependency and some code that uses it.
Modify pom.xml
to include a dependency for jscience
by adding the following code inside the <dependencies>
element:
In file pom.xml
, on line 28 add:
<dependency>
<groupId>org.jscience</groupId>
<artifactId>jscience</artifactId>
<version>4.3.1</version>
</dependency>
Now add the following import
statements to src/main/java/com/example/Main.java
to import the library:
In file src/main/java/com/example/Main.java
, on line 19 add:
import static javax.measure.unit.SI.KILOGRAM;
import javax.measure.quantity.Mass;
import org.jscience.physics.model.RelativisticModel;
import org.jscience.physics.amount.Amount;
Add the following hello
method to Main.java
:
In file src/main/java/com/example/Main.java
, on line 59 add:
@RequestMapping("/hello")
String hello(Map<String, Object> model) {
RelativisticModel.select();
Amount<Mass> m = Amount.valueOf("12 GeV").to(KILOGRAM);
model.put("science", "E=mc^2: 12 GeV = " + m.toString());
return "hello";
}
Finally, create a src/main/resources/templates/hello.html
file with these contents:
In file src/main/resources/templates/hello.html
write:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout (~{::body},'hello')}">
<body>
<div class="container">
<p th:text="${science}"/>
</div>
</body>
</html>
Here’s the final source code for Main.java
- yours should look similar. Here’s a diff of all the local changes you should have made.
Now test your changes locally:
$ mvn clean install
...
[INFO] Installing /Users/rschneeman/Documents/projects/tmp/java-getting-started/docs/tmp/java-getting-started/pom.xml to /Users/rschneeman/.m2/repository/com/example/java-getting-started/1.0/java-getting-started-1.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.599 s
[INFO] Finished at: 2020-09-03T14:55:07-05:00
[INFO] ------------------------------------------------------------------------
$ heroku local web
...
2:55:13 PM web.1 | 2020-09-03 14:55:13.555 INFO 24685 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2:55:13 PM web.1 | 2020-09-03 14:55:13.683 INFO 24685 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2:55:14 PM web.1 | 2020-09-03 14:55:14.252 INFO 24685 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2:55:14 PM web.1 | 2020-09-03 14:55:14.318 INFO 24685 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 5000 (http) with context path ''
Visiting your application’s /hello
path at http://localhost:5000/hello, you should see some great scientific conversions displayed:
E=mc^2: 12 GeV = (2.139194076302506E-26 ± 1.4E-42) kg
Now you can deploy. Almost every Heroku deployment follows this same pattern. First, use the git add
command to stage your modified files for commit:
$ git add .
Next, commit the changes to the repository:
$ git commit -m "Demo"
Now deploy, just as you did previously:
$ git push heroku main
Finally, check that your updated code is successfully deployed:
$ heroku open hello
Define config vars
Heroku lets you externalize your app’s configuration by storing data such as encryption keys or external resource addresses in config vars.
At runtime, config vars are exposed to your app as environment variables. For example, modify src/main/java/com/example/Main.java
so that the method obtains an energy value from the ENERGY
environment variable:
In file src/main/java/com/example/Main.java
, on line 56 add:
@RequestMapping("/hello")
String hello(Map<String, Object> model) {
RelativisticModel.select();
String energy = System.getenv().get("ENERGY");
if (energy == null) {
energy = "12 GeV";
}
Amount<Mass> m = Amount.valueOf(energy).to(KILOGRAM);
model.put("science", "E=mc^2: " + energy + " = " + m.toString());
return "hello";
}
Now compile the app again so that this change is integrated by running mvn clean install
.
heroku local
automatically sets up your local environment based on the contents of the .env
file in your app’s root directory. Your sample app already includes a .env
file with the following contents:
ENERGY=20 GeV
Your own apps should not commit the .env
file to version control, because it often includes secure credentials. Include .env
in your repo’s .gitignore
file.
If you run the app with heroku local
and visit it at http://localhost:5000/hello, you’ll see the conversion value for 20 GeV.
To set the config var on Heroku, execute the following:
$ heroku config:set ENERGY="20 GeV"
Setting ENERGY and restarting stark-earth-43785... done, v7
ENERGY: 20 GeV
View the config vars that are set using heroku config
:
$ heroku config
=== stark-earth-43785 Config Vars
DATABASE_URL: postgres://wvqqlmnuucfedp:1cee98cbbc522774fcb5f2e17616de6367479f365ddcbcd0d2270ab7633a6367@ec2-52-1-95-247.compute-1.amazonaws.com:5432/dakrti8nqocdn7
ENERGY: 20 GeV
Deploy your updated application to Heroku to see this in action.
Start a one-off dyno
The heroku run
command lets you run maintenance and administrative tasks on your app in a one-off dyno. It can also lets you launch a REPL process attached to your local terminal for experimenting in your app’s environment, or code that you deployed with your application:
$ heroku run java -version
Running java -version on stark-earth-43785... connecting, run.7199 (Free)Running java -version on stark-earth-43785... up, run.7199 (Free)
openjdk version "1.8.0_262-heroku"
OpenJDK Runtime Environment (build 1.8.0_262-heroku-b10)
OpenJDK 64-Bit Server VM (build 25.262-b10, mixed mode)
If you receive an error, Error connecting to process
, then you might need to configure your firewall.
Don’t forget to type exit
to exit the shell and terminate the dyno.
Provision add-ons
Add-ons are cloud services that provide additional services for your application, such as databases, logging, and monitoring.
By default, Heroku stores your app’s 1500 most recent log lines. However, the full log stream is available as a service, and several logging add-ons are available that provide features such as log persistence, search, and alerting.
In this step you’ll provision one of these logging add-ons, Papertrail.
Provision the Papertrail add-on like so:
$ heroku addons:create papertrail
Creating papertrail on stark-earth-43785... free
Welcome to Papertrail. Questions and ideas are welcome (support@papertrailapp.com). Happy logging!
Created papertrail-asymmetrical-49820 as PAPERTRAIL_API_TOKEN
Use heroku addons:docs papertrail to view documentation
To help prevent abuse, provisioning an add-on requires account verification. If your account has not been verified, you will be directed to visit the verification site.
The add-on is now deployed and configured for your application. You can list your app’s active add-ons like so:
$ heroku addons
To see this particular add-on in action, visit your application’s Heroku URL a few times. Each visit generates more log messages, which should now be routed to the Papertrail add-on. Visit the Papertrail console to see the log messages:
$ heroku addons:open papertrail
Your browser will open up a Papertrail web console that shows the latest log events. The interface lets you search and set up alerts:
Use a database
Heroku provides managed data services for Postgres and Redis, and the add-on marketplace provides a variety of additional data services, including MongoDB and MySQL.
In this step you’ll learn about the free Heroku Postgres add-on that is provisioned automatically with all Java app deploys.
Heroku Postgres is itself an add-on, so you can use the heroku addons
command for an overview of the database provisioned for your app:
$ heroku addons
Add-on Plan Price State
──────────────────────────────────────────────── ───────── ───── ───────
heroku-postgresql (postgresql-rectangular-80148) hobby-dev free created
└─ as DATABASE
papertrail (papertrail-asymmetrical-49820) choklad free created
└─ as PAPERTRAIL
The table above shows add-ons and the attachments to the current app (stark-earth-43785) or other apps.
Listing your app’s config vars will display the URL that your app is using to connect to the database (DATABASE_URL
):
$ heroku config
=== stark-earth-43785 Config Vars
DATABASE_URL: postgres://wvqqlmnuucfedp:1cee98cbbc522774fcb5f2e17616de6367479f365ddcbcd0d2270ab7633a6367@ec2-52-1-95-247.compute-1.amazonaws.com:5432/dakrti8nqocdn7
ENERGY: 20 GeV
PAPERTRAIL_API_TOKEN: 1TSyA9kKG1uU9FUuWn4D
The heroku pg
command provides more in-depth information on your app’s Heroku Postgres databases:
$ heroku pg
=== DATABASE_URL
Plan: Hobby-dev
Status: Available
Connections: 0/20
PG Version: 12.4
Created: 2020-09-03 19:53 UTC
Data Size: 7.9 MB
Tables: 0
Rows: 0/10000 (In compliance)
Fork/Follow: Unsupported
Rollback: Unsupported
Continuous Protection: Off
Add-on: postgresql-rectangular-80148
This indicates that the app has a Hobby-dev
database (the free plan), running Postgres, currently with zero rows of data.
The example app you deployed already has database functionality, which you can reach by visiting your app’s /db
path. For example, if your app’s root URL is https://wonderful-app-287.herokuapp.com/
then visit https://wonderful-app-287.herokuapp.com/db
.
The code to access the database is straightforward. Here’s the method to insert values into a table called tick
:
@Value("${spring.datasource.url}")
private String dbUrl;
@Autowired
private DataSource dataSource;
@RequestMapping("/db")
String db(Map<String, Object> model) {
try (Connection connection = dataSource.getConnection()) {
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add("Read from DB: " + rs.getTimestamp("tick"));
}
model.put("records", output);
return "db";
} catch (Exception e) {
model.put("message", e.getMessage());
return "error";
}
}
@Bean
public DataSource dataSource() throws SQLException {
if (dbUrl == null || dbUrl.isEmpty()) {
return new HikariDataSource();
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
return new HikariDataSource(config);
}
}
This ensures that when you access your app using the /db
route, a new row is added to the tick
table, and all rows are then returned so that they can be rendered in the output.
The HikariCP database connection pool is initialized with the configuration value spring.datasource.url
, which is defined in src/main/resources/application.properties
like this:
spring.datasource.url: ${JDBC_DATABASE_URL:}
This sets spring.datasource.url
to the value in the JDBC_DATABASE_URL
environment variable, set by the database add-on, and establishes a pool of connections to the database.
Deploy your changes to Heroku. Now, when you access your app’s /db
route, you will see something like this:
Database Output
* Read from DB: 2014-08-08 14:48:25.155241
* Read from DB: 2014-08-08 14:51:32.287816
* Read from DB: 2014-08-08 14:51:52.667683
Assuming that you have Postgres installed locally, use the heroku pg:psql
command to connect to the remote database and see all the rows:
$ heroku pg:psql
psql (10.1, server 9.6.10)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.
DATABASE=> SELECT * FROM ticks;
tick
----------------------------
2018-03-01 20:53:27.148139
2018-03-01 20:53:29.288995
2018-03-01 20:53:29.957118
2018-03-01 21:07:28.880162
(4 rows)
=> \q
Read more about Heroku PostgreSQL.
A similar technique can be used to install MongoDB or Redis add-ons.
Next steps
Congratulations! You now know how to deploy an app, change its configuration, scale it, view logs, and attach add-ons.
Here’s some recommended reading to continue your Heroku journey:
- How Heroku Works provides a technical overview of the concepts you’ll encounter while writing, configuring, deploying, and running apps.
- The Java category provides more in-depth information on developing and deploying Java apps.
- The Deployment category provides a variety of powerful integrations and features to help streamline and simplify your deployments.