Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx's "reuseport" for same IP:PORT pair on different virtual hosts

Tags:

nginx

I'm right understand that it's wrong to use "reuseport" for same IP:PORT pair on different virtual hosts:

http {
     server {
          listen       192.168.0.1:80 reuseport;
          server_name  server1;
          …
     }
     server {
          listen       192.168.0.1:80 reuseport;
          server_name  server2;
          …
     }
}

This config gives me:

nginx: [emerg] duplicate listen options for 192.168.0.1:80 in /etc/nginx/vhosts/server1.local.conf:66

or

nginx: [emerg] listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use)

So I've to use unique IP:PORT pairs for every virtual host?

In same time server-wide "listen 80 reuseport;" works just fine, but is it doing same as per unique IP:PORT ?

like image 370
Oleg Neumyvakin Avatar asked May 31 '15 15:05

Oleg Neumyvakin


2 Answers

Answer to your last question - in nginx, the listen directive is only allowed in the server context (that means per virtual host).

According to manual:

The listen directive can have several additional parameters specific to socket-related system calls. These parameters can be specified in any listen directive, but only once for a given address:port pair.

So if you have more than 1 virtual host (server definition in nginx config), then you can use the reuseport option in any 1 of them. Non-socket related options (like ssl or spdy) can still be set for more than 1 listen directive.


SIDE NOTE: What the reuseport directive really does:

Nginx from version 1.9.1 supports setting the SO_REUSEPORT TCP socket parameter. In modern OS (Linux kernel since 3.9), this enables the kernel to have more socket listeners for each socket (ip:port).

Without it, when new connection arrives, kernel notified all nginx workers about it and all of them try to accept it.

With this option enabled, each worker has its own listening socket and on each new connection, kernel chooses one of them which will receive it - so there is no contention.

More info about benefits, drawbacks and benchmarks of reuseport option can be read on this Nginx blog post

like image 187
Marki555 Avatar answered Oct 05 '22 19:10

Marki555


Only one listen directive per port/ip pair should have the reuseport option.

So just remove the reuseport from server2 vhost.

like image 26
Krzysztof Avatar answered Oct 05 '22 19:10

Krzysztof