How to Deploy Spring Boot Application: Step-by-Step Guide
To deploy a
Spring Boot application, package it as an executable JAR using mvn clean package or gradle build, then run it with java -jar. You can deploy it on servers, cloud platforms, or containerize it with Docker for easy distribution.Syntax
Deploying a Spring Boot application typically involves these steps:
- Build the executable JAR: Use
mvn clean packageorgradle buildto create a runnable JAR file. - Run the JAR: Use
java -jar yourapp.jarto start the application. - Deploy to environment: Copy the JAR to a server, cloud, or container and run it there.
bash
mvn clean package java -jar target/yourapp.jar
Example
This example shows how to build and run a simple Spring Boot app locally.
java
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class HelloController { @GetMapping("/") public String hello() { return "Hello, Spring Boot!"; } }
Output
Running the app and visiting http://localhost:8080/ shows: Hello, Spring Boot!
Common Pitfalls
Common mistakes when deploying Spring Boot apps include:
- Not packaging the app as an executable JAR, causing startup failures.
- Forgetting to open the correct port (default 8080) on the server or firewall.
- Running the app without required environment variables or configuration files.
- Using
java -cpinstead ofjava -jarfor Spring Boot JARs.
bash
Wrong: java -cp target/yourapp.jar com.example.demo.DemoApplication Right: java -jar target/yourapp.jar
Quick Reference
Summary tips for deploying Spring Boot applications:
- Use
mvn clean packageorgradle buildto create executable JARs. - Run apps with
java -jar yourapp.jar. - Configure ports and environment variables properly.
- Consider Docker for containerized deployment.
- Use cloud services like AWS Elastic Beanstalk or Heroku for easy hosting.
Key Takeaways
Package your Spring Boot app as an executable JAR using Maven or Gradle.
Run the app with java -jar to start it anywhere with Java installed.
Ensure server ports and environment variables are correctly set.
Use Docker or cloud platforms for scalable and easy deployment.
Avoid running Spring Boot JARs with java -cp; always use java -jar.