Nginx Mysteriously Fails to Start

Here’s a weird error for you. You have Nginx running, you change the configuration, run sudo nginx -t and it tells you everything is fine. You try to restart the server and it fails. What’s going on? Here’s how to fix it.

So before I get into the fix, just know that running sudo nginx -t (if you’ve installed Nginx from your package manager) will test your configuration and make sure there’s nothing that would cause Nginx to fail to start.

In this particular case you may get no information and Nginx is reporting that there’s nothing wrong. So take a look at the Nginx error log by opening it with sudo less /var/log/nginx/error.log (Hint: press Ctrl + G) to scroll all the way to bottom of the file if its long and you don’t want to scroll forever).

If you get a message along the lines of the following then I can help you.

bind() to failed (98: Address already in use)
bind() to [::]:80 failed (98: Address already in use)
still could not bind()

This means there’s something running on port 80 or whichever port it says. It could actually be Nginx itself. You may end up with this sort of situation after working on the server over SSH. You may lose the connection, get a Brokern Pipe error, and when you log back in you think everything is normal but now suddenly Nginx has decided to do weird stuff. Yeah, that’s the technical term we use in the biz – “weird stuff”. So anyway, finally, how to fix this:

Run sudo fuser -k 80/tcp. This will kill anything using port 80. If your error references a different port then just edit that command as appropriate. Now you can sudo service nginx restart and you shuold be good to go again.

Server administration, Web development

« First five minutes on a new server Running background jobs with Express »