Nginx Tips

by Galoisplusplus - 二 19 7月 2016
Tags #Linux #CS #tech #nginx

最近在做server端开发,需要熟悉nginx,本渣也就在这里记录下自己遇到的一些问题。其实都比较小白,纯粹当作自我扫盲啦XD 本文将不定期更新。

nginx: [emerg] bind() to \<ip>:\<port> failed (98: Address already in use)

1
nginx: [emerg] bind() to <ip>:<port> failed (98: Address already in use)

端口被占用,可以用查看使用文件或socket的命令fuser来杀掉占用端口的进程:

1
$ sudo fuser -k <port>/tcp

此外,如果使用IPv6还可能出现如下报错:

1
nginx: [emerg] bind() to [::]:<port> failed (98: Address already in use)

这是由于nginx配置中有listen <port>;,又有listen [::]:<port>;所致。 根据nginx文档的描述:

By default, nginx will look up both IPv4 and IPv6 addresses while resolving.

也就是说,listen [::]:<port>;会同时监听IPv4和IPv6的流量,所以listen <port>;是重复配置,将它删掉即可。 如果只想使用IPv6可以采用:

1
listen [::]:<port> ipv6only=on;

参考

(SOF) nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

worker_connections are more than open file resource limit: 1024

这是因为nginx worker的用户打开的文件超过上限。

如果nginx配置中有worker_rlimit_nofile参数,则打开的文件数量上限由worker_rlimit_nofile决定(nofile=number of open files)。 那么worker_rlimit_nofile应该配多少呢?

在nginx配置的core module中找到worker_processes数量:

1
worker_processes  4;

在event module中找到worker_connections数量:

1
2
3
events {
    worker_connections  1024;
}

那么最大总连接数是worker_connections * worker_processes,每个active connection都会占用一个文件描述符(file descriptor),所以worker_rlimit_nofile最好大于worker_connections * worker_processes

参考

nginx worker_rlimit_nofile文档

(SOF) understanding max file descriptors for linux and nginx, and best value for worker_rlimit_nofile

(SOF) How can I observe what nginx is doing? (to solve: “1024 worker_connections are not enough”)

如果nginx配置中没有worker_rlimit_nofile参数,则采用系统默认的打开的文件数量上限。那么如何查看并修改这一上限呢?

首先在nginx配置的core module中找到nginx worker进程的用户:

1
user nginx;

在终端登入这一用户:

1
$ sudo su - nginx

查看文件描述符的硬上限:

1
$ ulimit -Hn

查看文件描述符的软上限:

1
$ ulimit -Sn

这里硬上限是严格不能超过的上限,不能增加。软上限属于警告性质的上限,可以调高,但也不能超过硬上限。

/etc/sysctl.conf中修改下述数值:

1
fs.file-max = 65536

使用以下命令加载新的配置:

1
$ sysctl -p

检查是否已更新:

1
$ cat /proc/sys/fs/file-max

一些资料提到修改/etc/security/limits.conf中nofile的软上限和硬上限:

1
2
3
4
* soft     nofile         65535
* hard     nofile         65535
root soft     nofile         65535
root hard     nofile         65535

这种方式至少需要nginx worker进程重启才能生效。

参考

ulimit manual

通过 ulimit 改善系统性能

What does “soft/hard nofile” mean on Linux

ulimit: difference between hard and soft limits

limits.conf manual

Making changes to /proc filesystem permanently

nginx uLimit 'worker_connections exceed open file resource limit: 1024'

do changes in /etc/security/limits.conf require a reboot?

How to configure linux file descriptor limit with fs.file-max and ulimit

How to increase maximum file open limit (ulimit) in Ubuntu?

Nginx: 24: Too Many Open Files Error And Solution

an upstream response is buffered to a temporary file

proxy_temp failed (13: Permission denied) while reading upstream

Comments