0
0
SpringbootHow-ToBeginner · 4 min read

How to Deploy Spring Boot to Heroku: Step-by-Step Guide

To deploy a Spring Boot app to Heroku, first create a Heroku app and add a Procfile specifying how to run your app. Then build your app with ./mvnw clean package and push your code to Heroku using git push heroku main. Heroku will detect the Java app, build it, and run it automatically.
📐

Syntax

Deploying Spring Boot to Heroku involves these key parts:

  • Procfile: Tells Heroku how to start your app.
  • pom.xml or build.gradle: Defines your Java build and dependencies.
  • Heroku CLI commands: Used to create app, add git remote, and push code.
bash
web: java -Dserver.port=$PORT -jar target/*.jar
💻

Example

This example shows a simple Spring Boot app deployment to Heroku using Maven.

Steps:

  • Create a Procfile with the command to run your jar.
  • Build your app with Maven wrapper.
  • Initialize git, create Heroku app, and push code.
bash
# Procfile content
web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar

# Terminal commands
./mvnw clean package
heroku create my-spring-app
git init
heroku git:remote -a my-spring-app
git add .
git commit -m "Deploy Spring Boot to Heroku"
git push heroku main
Output
remote: -----> Java app detected remote: -----> Building Java app with Maven remote: -----> Launching... remote: Released v1 remote: https://my-spring-app.herokuapp.com/ deployed to Heroku
⚠️

Common Pitfalls

Common mistakes when deploying Spring Boot to Heroku:

  • Not creating a Procfile or having wrong command causes app not to start.
  • Forgetting to set server.port to $PORT environment variable.
  • Not committing all files before pushing to Heroku.
  • Using the wrong branch name when pushing (Heroku expects main or master).
bash
Wrong Procfile:
web: java -jar target/demo.jar

Right Procfile:
web: java -Dserver.port=$PORT -jar target/demo.jar
📊

Quick Reference

StepCommand / FileDescription
1ProcfileDefines how Heroku runs your app with port binding
2./mvnw clean packageBuilds your Spring Boot jar file
3heroku create Creates a new Heroku app
4git initInitializes git repository if not done
5heroku git:remote -a Adds Heroku git remote
6git add . && git commit -m 'msg'Commits your code
7git push heroku mainPushes code to Heroku to trigger deployment

Key Takeaways

Always include a Procfile with the command to run your Spring Boot jar on Heroku.
Set the server port to Heroku's $PORT environment variable in the Procfile command.
Build your app with Maven or Gradle before deploying to Heroku.
Use Heroku CLI to create the app and push your code via git.
Commit all necessary files and push to the correct branch (usually main).