Nginx Tips
最近在做server端开发,需要熟悉nginx,本渣也就在这里记录下自己遇到的一些问题。其实都比较小白,纯粹当作自我扫盲啦XD 本文将不定期更新。
nginx: [emerg] bind() to \<ip>:\<port> failed (98: Address already in use)
1 | |
端口被占用,可以用查看使用文件或socket的命令fuser来杀掉占用端口的进程:
1 | |
此外,如果使用IPv6还可能出现如下报错:
1 | |
这是由于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 | |
参考
(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 | |
在event module中找到worker_connections数量:
1 2 3 | |
那么最大总连接数是worker_connections * worker_processes,每个active connection都会占用一个文件描述符(file descriptor),所以worker_rlimit_nofile最好大于worker_connections * worker_processes。
参考
(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 | |
在终端登入这一用户:
1 | |
查看文件描述符的硬上限:
1 | |
查看文件描述符的软上限:
1 | |
这里硬上限是严格不能超过的上限,不能增加。软上限属于警告性质的上限,可以调高,但也不能超过硬上限。
在/etc/sysctl.conf中修改下述数值:
1 | |
使用以下命令加载新的配置:
1 | |
检查是否已更新:
1 | |
一些资料提到修改/etc/security/limits.conf中nofile的软上限和硬上限:
1 2 3 4 | |
这种方式至少需要nginx worker进程重启才能生效。
参考
What does “soft/hard nofile” mean on Linux
ulimit: difference between hard and soft limits
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