Tom
Tom

Reputation: 2661

how to run gunicorn with django as non-root

I have a django application and I use gunicorn to run it. My script to start gunicorn looks like this:

django_path=/path/to/your/manage.py 
settingsfile=my_name  
workers=2 

cd $django_path
exec gunicorn --env DJANGO_SETTINGS_MODULE=app.$settingsfile app.wsgi --workers=$workers &

this works when I execute it. However, when I look at my database in my projectfolder (cd /path/to/your/manage.py && ll) I get this:

-rw-r--r-- 1 root root 55K Dec 2 13:33 db.sqlite3

Which means I need root permisson to do anyhting on the databse (for example do a createuser). So I looked around on Stackoverflow and tried a couple of things:

All of them started my app but the problem with the database remains (only root rights).

So how do I run that script as a non root user?

Upvotes: 0

Views: 2345

Answers (2)

Tom
Tom

Reputation: 2661

Ok, so I found out that db.sqlite3 will be create in django through the makemigrations and migrate commands which I ran from root.

Hence, the problems with the permissions. I switched to debian and ran the commands from there et voila:

-rw-r--r-- 1 debian debian 55K Dec 2 13:33 db.sqlite3

Upvotes: 0

baldr
baldr

Reputation: 2999

I have a script in my project's folder which I use to run gunicorn. Here is a header:

#!/bin/bash
CUR_DIR=$(dirname $(readlink -f $0))
WORK_DIR=$CUR_DIR
USER=myusername
PYTHON=/usr/bin/python3
GUNICORN=/usr/local/bin/gunicorn

sudo -u $USER sh -c "cd $WORK_DIR; $PYTHON -W ignore $GUNICORN -c $WORK_DIR/config/gunicorn/gunicorn.conf.py --chdir $WORK_DIR myappname.wsgi:application

Updated: Put the code below to the file /etc/init.d/myservice, make the root owner and give +x permissions for the owner.

#!/bin/bash
#chkconfig: 345 95 50
#description: Starts myservice
if [ -z "$1" ]; then
echo "`basename $0` {start|stop}"
   exit
fi

case "$1" in
start)
   sh /path/to/run_script.sh start &
;;

stop)
   sh /path/to/run_script.sh stop
;;
esac

Now you can use sudo service myservice start

I am sorry, I am not familiar with systemd yet, but with it it can be even easier.

Upvotes: 2

Related Questions