I have some web applications that I wrote with python flask. I know which port I started each one on and each was started using nohup. Each one was started with something like nohup python mywebapp.py &

When I look at my processes with ps, I only see something like

36697 ?        60-21:36:16 python
 36971 ?        63-19:11:43 python
 37038 ?        65-06:57:22 python
 37312 ?        54-23:33:16 python
 37442 ?        54-09:14:57 python
 37716 ?        47-19:45:17 python
 68019 ?        00:29:24 python
146568 ?        00:20:57 python
146699 ?        00:17:08 python
150622 ?        00:32:20 python

If I need to stop one particular web application, how can I get from a port number back to a python process id so that I can kill the process?

  • where does the port number get specified when you start(ed) them? – Jeff Schaller Jun 26 '18 at 16:21
  • @JeffSchaller Great question, that is specified within the python code, specifically with a call to start an app server with the flask library/framework. – Unknown Coder Jun 26 '18 at 16:25
  • So the parameter mywebapp.py is enough to determine the port? – Jeff Schaller Jun 26 '18 at 16:31

You can use lsof to find the process id associated with a known port number

lsof -i :*port*

Alternatively, you may wish to use netstat which can display all network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.

Try netstat -tulpn

  • This sounds like its along the right track but this server does not have lsof and I cant use apt-get. Are there any other commands similar to this that you would recommend? – Unknown Coder Jun 26 '18 at 16:31
  • 1
    if you have netstat you may be able to find it using netstat -tulpn. You may have to grep the output for it to be useful. – Tyler Chambers Jun 26 '18 at 16:35
  • 1
    That did it, thank you! I can see the ports and then it gives me the PID in the last column, this is perfect! – Unknown Coder Jun 26 '18 at 16:37

One other way is to add it to the flask app itself.

from os import getpid
print("Creating PID file.")
fh=open("/var/run/yourAppNameWithPort.pid", "w")
  • Is this something I would do before I startup the app or can I do it even while the app is running? – Unknown Coder Jun 26 '18 at 16:34
  • You'd add this to you app, it would happen on startup. I usually use argparse and pass in the pidfile name as an argument, but that is just my preference. – Joe M Jun 27 '18 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.