如何 运行 gunicorn with django as non-root

how to run gunicorn with django as non-root

我有一个 django 应用程序,我使用 gunicorn 运行 它。我启动 gunicorn 的脚本如下所示:

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 &

这在我执行时有效。但是,当我在我的项目文件夹 (cd /path/to/your/manage.py && ll) 中查看我的数据库时,我得到了这个:

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

这意味着我需要 root 权限才能在数据库上执行任何操作(例如执行 createuser)。所以我环顾了 Whosebug 并尝试了一些东西:

他们都启动了我的应用程序,但数据库的问题仍然存在(只有 root 权限)。

那么我如何 运行 作为非 root 用户使用该脚本?

我的项目文件夹中有一个脚本,用于 运行 gunicorn。这是一个 header:

#!/bin/bash
CUR_DIR=$(dirname $(readlink -f [=10=]))
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

已更新: 将下面的代码放入文件 /etc/init.d/myservice,让 root 成为所有者并赋予所有者 +x 权限。

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

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

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

现在您可以使用sudo service myservice start

对不起,我还不熟悉systemd,但有了它,它会更容易。

好的,所以我发现 db.sqlite3 将通过 makemigrationsmigrate 命令在 django 中创建,我从 root 运行。

因此,权限问题。我切换到 debian 和 运行 那里的命令 et voila:

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