簡體   English   中英

如何用django作為非root運行gunicorn

[英]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 )。 所以我瀏覽了Stackoverflow並嘗試了幾件事:

  • 我將整個腳本放在/etc/init.d/rc.local的頂部
  • 然后我將腳本作為腳本文件gunicorn_script.sh放入/etc/init.d ,做了/usr/sbin/update-rc.d -f gunicorn_script.sh defaults
  • 最后,我嘗試將此命令放在rc.local文件的頂部: su debian -c '/etc/init.d/gunicorn_script.sh start' etc/ su debian -c '/etc/init.d/gunicorn_script.sh start' gunicorn_script.sh su debian -c '/etc/init.d/gunicorn_script.sh start'以debian用戶身份執行gunicorn_script

所有這些都啟動了我的應用程序,但數據庫的問題仍然存在(只有root權限)。

那么如何以非root用戶身份運行該腳本呢?

我的項目文件夾中有一個腳本,用於運行gunicorn。 這是一個標題:

#!/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

更新 :將下面的代碼放在文件/etc/init.d/myservice ,創建root用戶並為所有者授予+x權限。

#!/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

現在你可以使用sudo service myservice start

對不起,我對systemd還不熟悉,但有了它可以更容易。

好的,所以我發現db.sqlite3將通過我從root運行的makemigrationsmigrate命令在django中創建。

因此,權限問題。 我切換到debian並從那里運行命令等瞧:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM