叙述
生产 Nginx error.log 出现异常
an upstream response is buffered to a temporary file /tmp/xxx while reading upstream
解决
主要的原因在于upstream请求HTTP头内容太大,大小超过了Nginx所设置的反向代理(proxy)的buffer值,只能写入到磁盘,所造成的结果就是某个请求会比较缓慢或者中断,比如图片经常无法显示,刷新之后又正常了等等。
关于Nginx的proxy buffer在proxy_buffering中有详细的说明:
When buffering is enabled, nginx receives a response from the proxied server as soon as possible, saving it into the buffers set by the proxy_buffer_size and proxy_buffers directives. If the whole response does not fit into memory, a part of it can be saved to a temporary file on the disk. Writing to temporary files is controlled by the proxy_max_temp_file_size and proxy_temp_file_write_size directives.
When buffering is disabled, the response is passed to a client synchronously, immediately as it is received. nginx will not try to read the whole response from the proxied server. The maximum size of the data that nginx can receive from the server at a time is set by the proxy_buffer_size directive.
也就是说proxy buffer由proxy_buffering
控制是否开启(默认开启),然后buffer的值由proxy_buffer_size
和proxy_buffers
进行设置,如果整个请求超过buffer,超出的部分会写入到temporary file
设置的文件中,写入临时文件的操作由proxy_max_temp_file_size
和proxy_temp_file_write_size
进行设置。
proxy_buffer_size用来设置后端HTTP头响应的缓冲区的大小,proxy_buffers用来设置后端数据缓冲区大小,后面包含两个参数:number和size,开辟指定number个长度为size大小read_buf用来存储body,并非连接初始化的时候开辟number个,而是当buf不够存响应body时新申请,最多申请number个。除此之外,还有一个proxy_busy_buffers_size参数,该参数用于设置高负荷下缓冲大小,即当后端响应没有完全读取完毕之前,可以优先发送给客户端的缓存大小,其值是proxy_buffers和proxy_buffer_size的一部分,通常设置为proxy_buffer_size的两倍。
综合以上的说明并根据服务器实际的情况,将上述参数的值设置如下:
proxy_buffering on;
proxy_buffer_size 512k;
proxy_buffers 64 512k;
proxy_busy_buffers_size 1m;