September 10, 2011

To configure a Tornado server to run behind an nginx proxy is relatively easy. The following steps were using to configure a Ubuntu 10.10 server:

  • Start the Tornado server on some non-standard port - e.g. 8888
  • Tell nginx to proxy requests to your Tornado server on port 8888
  • Optionally you can have nginx handle all the static content (e.g. images, css, etc.) to reduce the load on the Tornado server

Configuring the Tornado server to run on a port is as simple as modifying the parameter passed to the listen function of the application object.

application = tornado.web.Application(routes, **settings)
application.listen(8888)

And then configure nginx to pass requests to your Tornado server. The following configuration snippet is meant to be included from the default Ubuntu 10.10 nginx server configuration. It includes the optional third step which tries to serve a static page from the filesystem before passing the request off the the upstream tornado server.

upstream example_servers {
  server 127.0.0.1:8888;
}

server {
  listen 80;
  server_name www.example.com;
  access_log /var/log/nginx/example.access.log;

  location / {
    root /opt/example/static;
    try_files $uri @example;
  }

  location @example {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass       http://example_servers;
  }
}

This snippet assumes the name of your site is "example" and it is located in /opt. To use it replace the "example" string with the actual name of your project.