获取502错误并使用Django、Nginx和Gunicorn发送邮件
我正在尝试在我的网站服务器上使用 Django 的 send_mail 函数通过 Gmail 的 SMTP 发送邮件,但遇到了 502 Bad Gateway 错误。
我使用的是 nginx 和 gunicorn。
这是我的错误日志:
2014/04/12 16:46:55 [error] 26846#0: *11 upstream prematurely closed connection while
reading response header from upstream, client: 179.162.163.62, server: example.com,
request: "POST /contact/ HTTP/1.1", upstream: "http://127.0.0.1:9000/contact/", host:
"example.com", referrer: "http://example.com/contact/"
nginx 配置文件:
upstream example_gunicorn {
server 127.0.0.1:9000 fail_timeout=0;
}
server {
listen 80;
client_max_body_size 4G;
server_name .example.com;
keepalive_timeout 5;
location /static/ {
alias /deploy/sites/example/static/; # STATIC_ROOT
expires 30d;
}
location /media/ {
alias /deploy/sites/example/media/; # MEDIA_ROOT
expires 30d;
}
location / {
# checks for static file, if not found proxy to app
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://example_gunicorn;
}
}
3 个回答
0
试着编辑一下你的 /etc/hosts 文件
127.0.0.1 localhost.localdomain localhost example.com
127.0.0.1 localhost
另外,增加一下你的 proxy_read_timeout 60s;
设置可能也会有帮助。在服务器配置中,默认是60秒,但你可以把它改成360秒或者其他的时间。别忘了重启服务(比如网络、nginx、postfix等)
2
我在DigitalOcean上使用CentOS7的时候遇到了类似的问题。我用的是Django 1.6.5和gunicorn。
我通过在settings.py
里明确指定EMAIL_HOST = "74.125.22.108"
来解决这个问题,而不是用EMAIL_HOST = "smtp.gmail.com"
。在我的情况下,这是一个IPv6的问题,因为DigitalOcean不支持通过IPv6发送SMTP邮件。
注意:出于安全考虑,使用dig
或类似工具在随便把smtp.gmail.com的IPv4地址粘贴到代码里之前,最好先确认一下这个地址。
4
502这个错误并没有告诉我们具体出了什么问题……我给你画个图:
Client/Browser Server Web Server
| request | |
|------------------------>| |
| | attempt to send mail |
| |-------------------------> |
| | ERROR
| | error message |
| |<--------------------------|
| 502 | |
|<----------------------- | |
图中的箭头代表着不同的交流过程。往下看,时间是逐渐增加的。
所以,网络服务器会把真实的错误信息隐藏起来,这在实际使用中是比较合理的做法。你需要查看网络服务器的日志来找到问题所在。