AWS EC2中Django runserver 8000端口域名访问异常问题咨询
Hey there! Let's get your site working without needing to append :8000 to your domain. Here are the most practical solutions tailored to your AWS EC2 setup:
1. Use Nginx as Reverse Proxy (Recommended for Production)
This is the go-to method for production environments—it's stable, secure, and handles traffic efficiently.
Install Nginx
On Ubuntu/Debian:sudo apt update && sudo apt install nginxOn Amazon Linux/CentOS:
sudo yum install nginxStart and enable Nginx
sudo systemctl start nginx sudo systemctl enable nginxConfigure reverse proxy
- Back up the default config first:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak - Edit the config file:
sudo nano /etc/nginx/sites-available/default - Replace the default
serverblock with this (replaceyour-domain.comwith your actual domain):server { listen 80; server_name your-domain.com; location / { proxy_pass http://127.0.0.1:8000; 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; } } - Check if the config is valid:
sudo nginx -t - Restart Nginx to apply changes:
sudo systemctl restart nginx
- Back up the default config first:
Update EC2 Security Group
Add an inbound rule allowing traffic on port 80 (TCP, from 0.0.0.0/0 or your desired source).
2. Port Forwarding with iptables (Quick Temporary Fix)
If you need a quick workaround for testing (not recommended for production), use iptables to forward port 80 traffic to 8000:
Run this command to set up forwarding:
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000Save the rule so it persists after reboot:
- Ubuntu/Debian: Install
iptables-persistentand follow prompts to save rules:sudo apt install iptables-persistent - Amazon Linux/CentOS:
sudo service iptables save
- Ubuntu/Debian: Install
Don't forget to open port 80 in your EC2 Security Group.
3. Run Django Directly on Port 80 (Not Recommended for Production)
Django's built-in runserver is meant for development only—it's not optimized for performance or security. But if you're just testing:
Run the server with root privileges (since port 80 is a privileged port):
sudo python manage.py runserver 0.0.0.0:80Again, ensure port 80 is open in your EC2 Security Group.
Important Notes
- Double-check that your domain is correctly pointed to your EC2 instance's public IP or Elastic IP.
- If you're using a CDN like Cloudflare, make sure it's configured to pass traffic to port 80 on your EC2 instance.
- For long-term production use, pair Nginx with a production-grade WSGI server like Gunicorn or uWSGI instead of relying on Django's
runserver.
内容的提问来源于stack exchange,提问作者DeltaModz

