AWS Lightsail部署的Bitnami Django站点显示默认首页,如何配置默认端口访问
问题根因
python manage.py runserver是Django官方提供的仅用于本地开发调试的轻量服务器,性能差、无安全防护、无守护进程,你指定监听8000端口,自然只能通过IP:8000访问服务,且你断开SSH连接后该服务会自动终止,完全不适用生产环境对外暴露。- 你使用的Bitnami预装环境默认在HTTP标准端口80上运行了自带的Web服务(Apache或Nginx),所以直接访问静态IP会跳转Bitnami默认首页。
生产级配置方案(直接通过80端口访问Django站点)
采用「Gunicorn做WSGI服务器 + Systemd做进程守护 + Bitnami自带Web服务做反向代理」的标准部署架构,步骤如下:
1. 安装并测试Gunicorn
进入你的Django项目虚拟环境,执行以下命令安装:
pip install gunicorn
进入项目根目录(即manage.py所在目录),测试Gunicorn是否能正常拉起项目:
gunicorn --bind 0.0.0.0:8000 你的项目名.wsgi
此时访问静态IP:8000能正常打开站点说明配置正确,按Ctrl+C停止测试即可。
2. 配置Systemd守护Gunicorn进程
配置后可实现Gunicorn后台运行、异常自动重启、开机自启。
执行命令新建服务配置文件:
sudo nano /etc/systemd/system/gunicorn.service
将以下内容填入文件,注意替换为你自己的项目路径、虚拟环境路径、项目名:
[Unit] Description=gunicorn daemon After=network.target [Service] User=bitnami Group=www-data WorkingDirectory=你的项目根目录绝对路径 ExecStart=你的虚拟环境绝对路径/bin/gunicorn --access-logfile - --workers 3 --bind unix:/tmp/gunicorn.sock 你的项目名.wsgi:application [Install] WantedBy=multi-user.target
保存退出后执行以下命令启动服务并设置开机自启:
sudo systemctl daemon-reload sudo systemctl start gunicorn sudo systemctl enable gunicorn
执行sudo systemctl status gunicorn验证状态,显示active (running)即为配置正常。
3. 修改Bitnami自带Web服务配置,转发80端口请求到Gunicorn
先执行命令确认你使用的Web服务类型:
sudo /opt/bitnami/ctlscript.sh status
根据输出的Web服务是Apache还是Nginx,选择对应配置:
若使用Nginx
新建/编辑站点配置文件:
sudo nano /opt/bitnami/nginx/conf/server_blocks/django.conf
填入以下配置,替换为你的实际信息:
server { listen 80 default_server; server_name 你的静态IP 如有域名也可填在此处; location / { proxy_pass http://unix:/tmp/gunicorn.sock; 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; } location /static/ { alias 你的项目静态文件目录绝对路径; } location /media/ { alias 你的项目媒体文件目录绝对路径; } }
测试配置合法性后重载服务:
sudo /opt/bitnami/nginx/sbin/nginx -t sudo /opt/bitnami/ctlscript.sh restart nginx
若使用Apache
编辑默认站点配置文件:
sudo nano /opt/bitnami/apache2/conf/bitnami/bitnami.conf
找到默认的<VirtualHost *:80>块,替换为以下内容,替换为你的实际信息:
<VirtualHost *:80> ServerName 你的静态IP 如有域名也可填在此处 DocumentRoot 你的项目根目录绝对路径 ProxyPass / unix:/tmp/gunicorn.sock|http://localhost/ ProxyPassReverse / unix:/tmp/gunicorn.sock|http://localhost/ Alias /static/ 你的项目静态文件目录绝对路径 <Directory 你的项目静态文件目录绝对路径> Require all granted </Directory> Alias /media/ 你的项目媒体文件目录绝对路径 <Directory 你的项目媒体文件目录绝对路径> Require all granted </Directory> </VirtualHost>
重载Apache服务:
sudo /opt/bitnami/ctlscript.sh restart apache
4. 放行Lightsail防火墙80端口
登录Lightsail控制台,进入实例详情的「网络」页,确认防火墙规则已添加HTTP 80端口的放行规则,无则新增保存即可。
配置完成后直接访问你的静态IP,即可无需加端口直接访问Django站点。
内容的提问来源于stack exchange,提问作者Marcos
相关产品推荐
相关产品推荐

