Killing a running server in Rails or Sinatra with a bash script
Quick update on my journey:
I’m four weeks into my coding boot camp and we are now moving on to Rails! Rails is a full stack web development framework that builds the tedious parts of coding so that developers can focus on more important things, such as the logic of the application. So far, I’m loving it! I‘m excited that I can build applications and see them come to life on a web browser.
The problem
This week, I came across an error while working on a Rails lab:
I ran into a similar error earlier in the week while working on another web app called Sinatra:
The two errors are basically the same and mean the port I am trying to reach (3000 for Rails, and 9393 for Sinatra) is currently in use. This usually happens when I forget to close the server after I’m done with a lab. In order to use the port, I have to kill the server. So in doing research, I discovered I can kill any server with the following commands and instructions:
lsof -i :<PORT NUMBER>
(i.e.lsof -i :3000
)- Obtain the unique
PID
(process identifier) fromlsof -i
output kill -QUIT <PID>
(i.e.kill -QUIT 4091
)
It worked!
However, I ran into this problem twice. Which means I looked up these commands twice. I’ve been told that “as developers, we are lazy.” If I come across this problem again and didn’t remember the commands, it would be daunting to look them up again. My campus manager suggested I turn these into a bash script. That way I could turn these commands into something I would remember. I followed this blog to help me do so. Below is the result.
Executable bash script
This executable bash script will walk me through the process of killing a server that is currently running.
#!
interprets the file as an executable/bin/bash
locates where the bash interpreter isecho
prints to the command lineread
takes user input and stores it into a variable (i.e.port
andpid
)${port}
and${pid}
interpolates these variables into the commands
Here is an example:
Important things to note:
- In order to use
./kill-server
, I had to be in the home directory. Thecd
command quickly got me there. - To continue working on the lab I had to hop back to the root directory of the lab. The
cd —
command brought me to my previous directory.
So the next time I come across this problem, I’ll just have to use my new bash script, ./kill-server
, instead of searching for the commands. I found this pretty fun to make! I’m looking forward to building more when different problems or ideas come up.
Happy coding! 😁