nginx 出现Cannot assign requested address问题分析
问题描述:
2019/02/14 15:45:30 [crit] 12608#0: *109984486 connect() to 127.0.0.1:80 failed (99: Cannot assign requested address) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET /picture/554495.jpg HTTP/1.0", upstream: "http://127.0.0.1:80/picture/554495.jpg", host: "127.0.0.1"
nginx报这个错
nginx配置:如下
location ~* /picture\/(\d+)\.(gif|jpg|jpeg|png)$ {
expires 24h;
root /picture/;#指定图片存放路径
access_log /usr/local/nginx/logs/images.log;#日志存放路径
proxy_store on;
proxy_store_access user:rw group:rw all:rw;
proxy_temp_path /picture/;#图片访问路径
proxy_redirect off;
proxy_set_header Host 127.0.0.1;
client_max_body_size 10m;
client_body_buffer_size 1280k;
proxy_connect_timeout 900;
proxy_send_timeout 900;
proxy_read_timeout 900;
proxy_buffer_size 40k;
proxy_buffers 40 320k;
proxy_busy_buffers_size 640k;
proxy_temp_file_write_size 640k;
if ( !-e $request_filename)
{
proxy_pass http://127.0.0.1;#默认80端口
}
}
原因分析:原有的80端口请求已经太多,有大量的socket连接没有释放,图片请求访问仍然去访问80端口
只有不让访问80端口就可以不报这个错误了
网上解决办法(使用这个方法之后还是会报错)
使用Amazon EC2和弹性IP,服务器并不像大多数其他服务器那样知道其IP。
所以你需要告诉你的linux允许进程绑定到非本地地址。只需将以下行添加到/etc/sysctl.conf
文件中:
# allow processes to bind to the non-local address # (necessary for apache/nginx in Amazon EC2) net.ipv4.ip_nonlocal_bind = 1
然后通过以下方式重新加载sysctl.conf:
$ sysctl -p /etc/sysctl.conf
重新启动就行了:
-----
最后 将以下代码注释掉就没错了
if ( !-e $request_filename)
{
proxy_pass http://127.0.0.1;#默认80端口
}
----------
http://dev.cbs.bacic5i5j.com/picture/554495.jpg 再次访问的时候报
2019/02/14 16:13:05 [error] 13308#0: *110623237 open() "/picture/picture/554495.jpg" failed (2: No such file or directory), client: 10.1.20.35, server: localhost, request: "GET /picture/554495.jpg HTTP/1.1", host: "dev.cbs.bacic5i5j.com"
发现图片路径后面多了一个picture
root /picture/;#指定图片存放路径
把这个改成 root /;
就可以了
最后完成的nginx配置如下
location ~* /picture\/(\d+)\.(gif|jpg|jpeg|png)$ { expires 24h; root /;#指定图片存放路径 access_log /usr/local/nginx/logs/images.log;#日志存放路径 proxy_store on; proxy_store_access user:rw group:rw all:rw; proxy_temp_path /picture/;#图片访问路径 proxy_redirect off; proxy_set_header Host 127.0.0.1; client_max_body_size 10m; client_body_buffer_size 1280k; proxy_connect_timeout 900; proxy_send_timeout 900; proxy_read_timeout 900; proxy_buffer_size 40k; proxy_buffers 40 320k; proxy_busy_buffers_size 640k; proxy_temp_file_write_size 640k; #if ( !-e $request_filename) #{ # proxy_pass http://127.0.0.1;#默认80端口 #} }