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/*.jarExample
This example shows a simple Spring Boot app deployment to Heroku using Maven.
Steps:
- Create a
Procfilewith 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
Procfileor having wrong command causes app not to start. - Forgetting to set
server.portto$PORTenvironment variable. - Not committing all files before pushing to Heroku.
- Using the wrong branch name when pushing (Heroku expects
mainormaster).
bash
Wrong Procfile: web: java -jar target/demo.jar Right Procfile: web: java -Dserver.port=$PORT -jar target/demo.jar
Quick Reference
| Step | Command / File | Description |
|---|---|---|
| 1 | Procfile | Defines how Heroku runs your app with port binding |
| 2 | ./mvnw clean package | Builds your Spring Boot jar file |
| 3 | heroku create | Creates a new Heroku app |
| 4 | git init | Initializes git repository if not done |
| 5 | heroku git:remote -a | Adds Heroku git remote |
| 6 | git add . && git commit -m 'msg' | Commits your code |
| 7 | git push heroku main | Pushes 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).