ubuntu安装nginx并绑定域名
FastAPI应用域名绑定配置指南
前提条件
- 已拥有一个域名(如:yourdomain.com)
- 域名已解析到服务器IP地址(175.27.253.177)
- 服务器已开放80/443端口
- FastAPI应用正在端口8000上运行
配置步骤
步骤1:安装Nginx
1 | # 更新系统包 |
步骤2:创建Nginx反向代理配置
创建Nginx配置文件:
1 | sudo nano /etc/nginx/sites-available/yourdomain.com |
将以下内容粘贴到配置文件中(替换yourdomain.com为实际域名):
1 | server { |
步骤3:启用Nginx配置
1 | # 创建符号链接启用配置sites-enabled/是启用的配置,sites-available/是可启用的配置 |
步骤4:配置SSL证书(可选但推荐)
使用Let’s Encrypt申请免费SSL证书:
1 | # 安装Certbot和Nginx插件 |
执行后1.输入邮箱 回车 2.同意协议 3.邮箱地址共享给基金会 4.选择2则是重定向域名的http到https
根据提示完成证书申请流程。Certbot会自动更新Nginx配置以启用HTTPS。
步骤4.1:SSL证书自动续期配置
Let’s Encrypt证书有效期为90天,Certbot默认会自动设置续期任务。以下是详细说明:
1. 检查自动续期是否已配置
1 | # 检查systemd定时器(Ubuntu 20.04+推荐方式) |
2. 手动设置自动续期(如果未自动配置)
方式1:使用systemd定时器1
2
3
4
5# 启用Certbot定时器
sudo systemctl enable --now certbot.timer
# 验证定时器状态
sudo systemctl status certbot.timer
方式2:使用cron作业1
2# 创建cron作业文件
sudo nano /etc/cron.d/certbot
添加以下内容(每天凌晨2点运行续期检查):1
0 2 * * * root certbot -q renew
3. 测试自动续期功能
1 | # 测试续期(--dry-run模拟续期过程) |
如果输出显示”Congratulations, all renewals succeeded.”,则自动续期配置正确。
4. 查看续期日志
1 | # 查看Certbot续期日志 |
5. 续期后自动重载Nginx
Certbot默认会在续期成功后自动重载Nginx配置。可以通过查看Certbot配置确认:
1 | cat /etc/letsencrypt/renewal/api.ddda.cc.conf | grep -i reload |
输出为空自动续期但是不会,自动加载新的ssl,
如果没有自动重载配置,可以手动添加:1
sudo nano /etc/letsencrypt/renewal/yourdomain.com.conf
在文件末尾添加:1
2
3
4
5
6
7
8[renewalparams]
post_hook = systemctl reload nginx
或deploy-hook = systemctl reload nginx
```bash
post_hook = systemctl reload nginx 是在续期成功后,通过systemctl reload nginx命令来重新加载Nginx配置。
deploy-hook = systemctl restart nginx 是在续期成功后,通过systemctl restart nginx命令来重启Nginx服务。
两种方式都可以实现自动加载新的SSL证书,但是reload是在不中断服务的情况下重新加载配置,而restart是先停止服务,然后再启动服务,所以restart会有短暂的服务中断。
根据实际情况选择合适的方式。
总结
通过以上步骤,您的FastAPI应用现在应该可以通过域名访问了。配置包括:
- Nginx作为反向代理服务器
- 域名解析和绑定
- SSL证书配置(HTTPS支持)
- 系统服务配置(自动重启)
这样可以确保应用的稳定运行和安全访问。