第一步:安装 Nginx
在 Ubuntu/Debian 上安装
-
更新包列表:
bashsudo apt update
-
安装 Nginx:
bashsudo apt install nginx
-
启动 Nginx 并设置开机启动:
bashsudo systemctl start nginx sudo systemctl enable nginx
-
验证 Nginx 是否成功启动:
bashsudo systemctl status nginx
在 CentOS/RHEL 上安装
-
更新包列表:
bashsudo yum update
-
安装 Nginx:
bashsudo yum install epel-release sudo yum install nginx
-
启动 Nginx 并设置开机启动:
bashsudo systemctl start nginx sudo systemctl enable nginx
-
验证 Nginx 是否成功启动:
bashsudo systemctl status nginx
第二步:配置 Nginx
配置 Nginx 服务器块
-
创建一个新的 Nginx 服务器块配置文件:
bashsudo nano /etc/nginx/conf.d/example.com.conf
-
编辑配置文件:
nginxserver { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; # 重定向 HTTP 到 HTTPS } server { listen 443 ssl; # 监听 HTTPS 请求 server_name example.com www.example.com; # SSL 证书路径 ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # 配置 SSL 设置 ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_protocols TLSv1.2 TLSv1.3; # 使用最新的安全协议 ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { proxy_pass http://localhost:8080; # 将请求转发给 Java 应用 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; 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; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-NginX-Proxy true; } # 自定义错误页面 error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
-
保存并关闭配置文件。
-
测试配置:
bashsudo nginx -t
-
重启 Nginx 以使更改生效:
bashsudo systemctl restart nginx
第三步:部署 Java 应用
-
安装 Java 运行环境:
bashsudo apt install openjdk-11-jdk # 对于 Ubuntu/Debian sudo yum install java-11-openjdk-devel # 对于 CentOS/RHEL
-
安装 Tomcat:
bashsudo apt install tomcat9 # 对于 Ubuntu/Debian sudo yum install tomcat # 对于 CentOS/RHEL
-
部署 Java 应用:
- 将
.war
或.jar
文件放到 Tomcat 的webapps
目录下。 - 如果是
.war
文件,Tomcat 会自动解压并部署。 - 如果是
.jar
文件,需要手动配置context.xml
并放置在webapps/ROOT/WEB-INF
目录下。
- 将
-
启动 Tomcat:
bashsudo systemctl start tomcat9 # 对于 Ubuntu/Debian sudo systemctl start tomcat # 对于 CentOS/RHEL
-
设置 Tomcat 开机启动:
bashsudo systemctl enable tomcat9 # 对于 Ubuntu/Debian sudo systemctl enable tomcat # 对于 CentOS/RHEL
-
验证 Tomcat 是否启动成功:
bashsudo systemctl status tomcat9 # 对于 Ubuntu/Debian sudo systemctl status tomcat # 对于 CentOS/RHEL
第四步:获取 SSL 证书
-
安装 Certbot:
bashsudo apt install certbot python3-certbot-nginx # 对于 Ubuntu/Debian sudo yum install certbot python3-certbot-nginx # 对于 CentOS/RHEL
-
获取并设置证书:
bashsudo certbot --nginx -d example.com -d www.example.com
-
自动续期证书:
bashsudo systemctl restart nginx
完成上述步骤后,Nginx 服务器可以处理 HTTP 和 HTTPS 请求,并将流量转发到 Tomcat 中的 Java 应用。
注意事项
- 确保防火墙允许 HTTP (80) 和 HTTPS (443) 流量。
- 根据实际需要调整 SSL 设置。
- 检查 Tomcat 日志以解决部署问题。