1. Launch EC2 & Connect via SSH
2. Install Java
sudo apt update
sudo apt install openjdk-17-jdk -y
java -version
3. Upload or Clone Java App
scp -i "your-key.pem" your-app.jar ec2-user@your-ec2-ip:/home/ec2-user
# OR
# git clone https://github.com/yourrepo/spring-boot-app.git
4. Run Java App
java -jar your-app.jar
5. Create systemd Service
sudo nano /etc/systemd/system/javaapp.service
[Unit]
Description=Java Spring Boot App
After=network.target
[Service]
User=ec2-user
WorkingDirectory=/home/ec2-user
ExecStart=/usr/bin/java -jar your-app.jar
SuccessExitStatus=143
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reexec
sudo systemctl start javaapp
sudo systemctl enable javaapp
6. Apache as Reverse Proxy (HTTPS)
sudo apt install apache2 -y
sudo a2enmod proxy proxy_http ssl
sudo nano /etc/apache2/sites-available/javaapp.conf
<VirtualHost *:80>
ServerName yourdomain.com
ProxyPreserveHost On
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
</VirtualHost>
sudo a2ensite javaapp
sudo systemctl restart apache2
Enable HTTPS
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache
7. Nginx as Reverse Proxy
sudo apt install nginx -y
sudo nano /etc/nginx/sites-available/javaapp
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
sudo ln -s /etc/nginx/sites-available/javaapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
Enable HTTPS
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com
8. Final Tips
- Use
screen
or tmux
if not using systemd
- Use environment variables via
.env
or systemd Environment=
- Use SSL always in production