I've been following a few tutorials online on how to setup Django, Postgres, Gunicorn and Nginx in production. I noticed that it is always recommended to install all Python dependencies inside the virtual environment. This includes Gunicorn.
For example, we fire up our virtual environment initially, then execute the 'manage.py runserver 0.0.0.0:8000' command, we then test if Gunicorn binds to it. Once we see that Gunicorn works we then deactivate our virtual environment to start configuring Nginx. It is never mentioned to enable our virtual environment again.
How is Gunicorn able to process requests when it lives inside the virtual environment, which had been deactivated? I assume there is a mechanism somewhere wherein the virtual environment is enabled again automatically. But where and when is the virtual environment enabled? And how is it enabled?
I've tried looking for answers online and in tutorials, but I still can't find anything that explains it fully.
Deactivating the virtual environment doesn't change anything for gunicorn
, because the virtual environment is just an execution context - a path to where binary dependencies are located - and deactivating it doesn't destroy it.
When you deactivate that execution context, it's only the current instance of your shell (that specific terminal window let's say) that exits it. Other things that rely on that execution context can still use it freely, including processes that were spawned in that same shell instance at a prior time.
In fact - I don't have a citation for this - but AFAIK Python pulls the entire execution context into memory, so regardless of what happens to shell sessions or environments elsewhere probably does not matter a lick. The app has everything it needs already loaded and won't release it until the app's main process exits.
The reason it's hard to find material that covers this in depth is probably because it's not a Python thing, or a virtual environment thing, it's related to how the operating system manages processes and memory - which is not necessarily a simple topic.