Search code examples
bashnginxpid

<bash> Get PID of all active nginx connections and kill single one


I need to kill process ID from an established nginx connection to worker process.

Is there a way to get PID from all nginx established connections?

If i do netstat on nginx worker processes, i am getting pids from worker processes which need to stay alive after I kill process that is connected to it.

I've tried with netstat -anp | grep "client_ip_address" | grep ESTABLISHED

and i am getting this:

tcp   0  0  client_ip:dest_port  client_ip:source_port   ESTABLISHED 15925/nginx: worker

so 15925 would be the process ID that needs to stay alive when i kill the connection to it.

Is there a way to do it?


Solution

  • I think maybe you're confusing Process IDs and Connections. Nginx starts a master process which then spawn off a handful of worker processes. You might only have (say) 5 workers on a fairly busy system.

    As connections come in, nginx wakes up and one of the workers is assigned to that connection. From then on, any TCP traffic that flows goes from the remote client to that worker process. Workers can each handle a large number of connections. Most HTTP connections only last for a few seconds, so as they close, they make space for the worker to take on more new connections.

    So... if you're trying to use the shell command 'kill', the best you could ever do would be to terminate one of the worker processes, which would close (potentially) a large number of connections.

    If your aim is to disconnect one client, whilst leaving all the others connected you're out of luck. There isn't a way to do this with shell commands. If your HTTP connections are hanging around for a long time (like Websockets do, for example), then its possible you could write something on the application side which allows you to close connections that you don't like.

    One more thing you may be thinking of is to close connections from places you don't like (a sort of 'spam' blocker). The more usual way to do this is just to reject the connection out-right so it uses as few of your resources as possible. Again, this is something you can do dynamically on the application side, or else you could put something like Naxsi (https://github.com/nbs-system/naxsi/wiki) and fail2ban together (https://github.com/nbs-system/naxsi/wiki/A-fail2ban-profile-for-Naxsi).