Deploying a Spring Boot application on an AWS EC2 instance
Deploying a Spring Boot application on an AWS EC2 instance involves several steps. Below is a comprehensive guide to get your application up and running:
1. Prepare Your Spring Boot Application
1. Build the JAR File: Use Maven or Gradle to build your Spring Boot application.
mvn clean package
This generates a target/*.jar file.
2. Test Locally: Ensure the application runs locally without issues:
java -jar target/your-application.jar
2. Launch an EC2 Instance
1. Log in to AWS Management Console:
- Navigate to the EC2 Dashboard.
2. Launch an Instance:
- Select an AMI (Amazon Linux 2 or Ubuntu is recommended).
- Choose an instance type (t2.micro for small apps under free tier).
- Configure instance details (e.g., security group, VPC).
3. Configure Security Group:
- Open ports:
1. 22 for SSH access.
2. 8080 or the port your Spring Boot app listens on.
- Add rules:
1. Source: Use your IP for SSH.
2. Source: Public access (0.0.0.0/0) for application access or restrict it as needed.
4. Key Pair:
- Create or use an existing key pair for SSH access.
3. Connect to the EC2 Instance
1. SSH into the Instance:
ssh -i "your-key.pem" ec2-user@your-ec2-public-ip
2. Update System Packages:
sudo yum update -y
3. Install Java: If Java is not installed, install it:
sudo yum install java-11-openjdk -yjava -version
4. Transfer the Application
1. Copy the JAR File: From your local system to the EC2 instance:
scp -i "your-key.pem" target/your-application.jar ec2-user@your-ec2-public-ip:/home/ec2-user/
5. Run the Spring Boot Application
1. Start the Application:
java -jar your-application.jar
2. Access the Application:
- Open your browser and navigate to http://<ec2-public-ip>:8080.
6. Set Up as a Background Service (Optional)
To keep the application running even after you log out:
1. Install screen or nohup:
sudo yum install screen -y
2. Run with screen:
screenjava -jar your-application.jar
Detach by pressing Ctrl+A, then D.
3. Run with nohup:
nohup java -jar your-application.jar
7. Optional - Use an Application Server (NGINX)
1. Install NGINX:
sudo yum install nginx -y
2. Configure Reverse Proxy: Update /etc/nginx/nginx.conf to route traffic to your application:
server { listen 80; server_name your-ec2-public-ip;
location / { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }}
3. Restart NGINX:
sudo systemctl restart nginx
4. Access the Application: Navigate to http://<ec2-public-ip>.