nginx and flask

I’ve been wanting to play with nginx for a while, and I have experimented a little with flask. But try as I might, I just could never understand how to get nginx and fastcgi to play with each other. Until bumby invited me to a hack night and he spent an hour or so showing me how to do it. I <3 bumby.

I can’t fault the documentation, in fact, the flask documentation on how to deploy flask with fastcgi under nginx should be quite sufficient (and indeed, now as I read it in retrospect, it is all crystal clear).

The problem I had was that I couldn’t divine how the fastcgi concept works, and I suppose this is mainly due to me having exclusively worked with Apache and PHP, which does stuff differently.

I just couldn’t wrap my head around how things would work out, if nginx didn’t know where the flask (Python) stuff was located.

I suppose that there is some part of the documentation which outlines precisely this, and that I read that part of the documentation poorly.

The “aha-moment” came when bumby made me realize that there won’t be one server process (web server) but two (web server and fastcgi server) and that these two processes won’t know where the other resides, and that this is ok, because they communicate through other means, namely sockets.

So the entire flow goes something like this:

  1. A client makes a request to the (nginx) web server, which determines that this is something to be handled by the fastcgi server, and thus sends it on through the socket
  2. The fastcgi server listens to the socket, handles the request and replies over the same socket
  3. The web server receives the reply and sends it on to the requesting client

Or at least, this is how I have come to understand the work flow.

Either way, the important thing to realize (which I couldn’t on my own) is that the configuration file for nginx won’t contain a path to the web stuff, as Apache would for a PHP-powered site.

This is ok, but quite contrary to what my mental model told me was necessary for the successful operation of a dynamic website. Once I understood the communication between nginx and fastcgi, it all made so much sense.

In case I ever forget it: client -> nginx -(socket)-> fastcgi -(socket)-> nginx -> client

Update: Typos be gone!


Tags: , ,

Comments are closed.