Quick Left

This is a blog

GIFs, tech and stuff.

Reverse Proxying Local Servers Through Nginx

There is a certain amount of difficulty in maintaining a sane development environment. For a while, Phusion Passenger solved this problem by allowing simple management of local development. However, with more Ruby developers using RVM, and maintaining applications built on different gemsets and rubies, Passenger has become an unworkable solution.

This setup will allow you to have nginx reverse proxy requests to unicorns, mongrels, webricks, thins, or whatever you really want to have run your servers. We create an environment that is similar to Phusion Passenger, but allows the developer more control and enables the use of RVM for different application environments.

Start your servers

These servers will now run (ideally) forever. I do it through screen so that I can always have a handle on the processes.

screen -S servers

From there, navigate to your server directory (we'll do one for now) and start it however you want: unicorn_rails, script/server, rails s, whatever you do.
Detach using Ctrl-A D. Resume using screen -r servers

Learning GNU screen is beyond the scope of this post - but it's super easy and allows terminal multiplexing/etc. A quick reference is all you really need, and is located HERE.

If you start up multiple servers, make sure to start them on different ports. Check your preferred flavor of server for documentation on this.

Configure Nginx

Install nginx. If you have homebrew, this is easy. 'brew nginx'. This should go quick because nginx is incredibly lightweight. The Nginx install process will also tell you how to load it on startup - this is probably a good idea, but don't do this until we've changed the configuration settings a bit.

Now let's swap Apache and Nginx.

sudo apachectl stop

Now, to prevent any ugly and weird things from happening, open your /etc/apache2/httpd.conf (assuming a system OSX install of Apache) file and change the listen port to something you'll never use. You can start apache again if you really want to.

sudo apachectl start

From here let's configure Nginx to use port 80 and do us some proxying.
This is located in: ~/Developer/etc/nginx/nginx.conf if you're using Cinderella, which you should probably be doing if you enjoy a sane development environment.

Here is my sample config:

What's going on here? Nothing magical - we're just making nginx listen on port 80, and anything with an alias of my_site.local gets routed to the upstream_server, which I've defined as localhost:3000 and is my unicorn server. To add more, add more upstream and server blocks, and rename them appropriately.

Now start nginx:

sudo nginx

Whenever you make config changes, reload it with:

sudo nginx -s reload

If you don't sudo it, OSX will become angry with you for attempting to attach a listener to port 80.

That's all you need to do! You can now access your sites through http://my_site.local.