关闭终端后EC2上Spring Boot应用Endpoint无法访问及安全问题求助
问题1:让Spring Boot应用后台持续运行
你当前用java -jar直接启动属于前台运行,SSH终端断开后,进程会被系统终止,导致网站无法访问。以下是三个实用解决方案:
方案1:用nohup实现后台运行(快速测试)
这是最简单的临时方案,适合验证需求:
nohup java -jar application-name-0.0.1-SNAPSHOT.jar > app.log 2>&1 &
nohup:让进程忽略终端断开信号,避免被终止> app.log 2>&1:将程序日志输出到app.log文件,方便后续排查问题&:让进程在后台运行
如需停止进程,先用ps aux | grep java找到进程ID,再执行kill <进程ID>即可。
方案2:用screen维持会话(需临时查看状态)
适合需要偶尔重新连接终端查看程序运行状态的场景:
- 安装screen(Amazon Linux默认已预装):
sudo yum install screen -y
- 创建新会话:
screen -S spring-app
- 在会话内启动应用:
java -jar application-name-0.0.1-SNAPSHOT.jar
- 按
Ctrl+A+D分离会话,此时关闭终端进程仍会持续运行 - 重新连接会话:
screen -r spring-app
方案3:配置systemd服务(生产环境推荐)
将应用注册为系统服务,实现开机自启,进程意外终止时自动重启:
- 创建服务配置文件:
sudo vi /etc/systemd/system/spring-app.service
- 粘贴以下内容(替换jar包路径和应用名称):
[Unit] Description=Spring Boot Application After=network.target [Service] User=ec2-user ExecStart=/usr/bin/java -jar /home/ec2-user/application-name-0.0.1-SNAPSHOT.jar Restart=always RestartSec=5 StandardOutput=journal+console StandardError=journal+console [Install] WantedBy=multi-user.target
- 重新加载systemd配置:
sudo systemctl daemon-reload
- 启动服务并设置开机自启:
sudo systemctl start spring-app sudo systemctl enable spring-app
- 查看服务状态:
sudo systemctl status spring-app
问题2:实现HTTPS安全连接
浏览器显示「Not Secure」是因为使用未加密的HTTP协议;直接用HTTPS访问8080失败是因为Spring Boot未配置SSL,8080端口默认走HTTP,HTTPS默认使用443端口。推荐采用Nginx反向代理+Let's Encrypt免费证书的方案,这也是生产环境的标准做法:
步骤1:安装Nginx
sudo yum install nginx -y sudo systemctl start nginx sudo systemctl enable nginx
步骤2:申请Let's Encrypt免费SSL证书
- 安装certbot工具:
sudo yum install certbot python3-certbot-nginx -y
- 申请证书(需先拥有域名,并将域名解析到EC2公网IP):
sudo certbot --nginx -d your-domain.com
按照提示输入邮箱、同意条款即可,certbot会自动完成SSL证书的配置。
步骤3:配置Nginx反向代理到Spring Boot
编辑certbot生成的Nginx配置文件(路径为/etc/nginx/conf.d/your-domain.com.conf),添加反向代理规则:
server { listen 443 ssl; server_name your-domain.com; # certbot自动生成的SSL配置 ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # 反向代理到Spring Boot的8080端口 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; } } # 将所有HTTP请求重定向到HTTPS server { listen 80; server_name your-domain.com; return 301 https://$host$request_uri; }
步骤4:重启Nginx并验证
sudo systemctl restart nginx
现在访问https://your-domain.com/login即可看到安全的加密连接,浏览器地址栏会显示锁形图标。
注意:需确保EC2安全组开放80(HTTP)和443(HTTPS)端口,8080端口可设置为仅允许本地访问(127.0.0.1),提升安全性。
内容的提问来源于stack exchange,提问作者ChloeCheerUp
相关产品推荐
相关产品推荐

