Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run gunicorn/a python app server as a non-root user? [closed]

I'm deploying a django app with gunicorn behind nginx on centos 5. How can I run gunicorn as a non-root user? None of the documentation seems to address this. This probably applies to any python application server running behind nginx as well...

I should add that the following doesn't work:

sudo -u nobody gunicorn_django --workers=4

It fails with:

raise HaltServer(reason, self.WORKER_BOOT_ERROR)
    gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>

Answer:

My mistake. I had a custom settings.py file so should have invoked gunicorn with:

sudo -u nobody gunicorn_django --workers=4 production_settings.py
like image 391
user1199438 Avatar asked Feb 13 '12 14:02

user1199438


1 Answers

I recommend using supervisord. Supervisor starts your app under the user account you tell it at boot.

Here's my my_app.conf which I place under /etc/supervisor/conf.d/:

[program:my_app]
command=/home/some_user/my_app/run_gunicorn
directory=/home/some_user/my_app
user=some_user                  
redirect_stderr=true            
stdout_logfile=/home/some_user/supervisord_stdout.txt
stdout_logfile_maxbytes=20MB
stdout_logfile_backups=10

My run_gunicorn script is then:

#!/bin/bash
source /home/some_user/virtualenvs/my_app_virtualenv/bin/activate
exec /home/some_user/virtualenvs/my_app_virtualenv/bin/gunicorn -c gunicorn.conf   wsgi:application

I could reference gunicorn directly in my_app.conf, but I don't because this way I can run activate. I put my DJANGO_SECRET at the tail end of my activate script as an env var. It's also good to do that with API keys and other sensitive stuff that doesn't belong in Git or Mercurial.

My gunicorn.conf is:

backlog = 2048
bind = "127.0.0.1:9000"
pidfile = "/home/some_user/gunicorn-my_app.pid"
daemon = False
debug = False
workers = 3
logfile = "/home/some_user/gunicorn-my_app.log"
loglevel = "info"
timeout = 90

Actually I'm sure there could be improved, but they get my app running without being root. Supervisord ensures the app server stays running. I then point nginx at my app server via proxy_pass (can share that too if needed).

EDIT: clarifying filenames

like image 57
Jeremy Avatar answered Sep 22 '22 09:09

Jeremy