Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Eduard-gan/ddefa96d966e3032aaaa93c1c44e9979 to your computer and use it in GitHub Desktop.
Save Eduard-gan/ddefa96d966e3032aaaa93c1c44e9979 to your computer and use it in GitHub Desktop.
Запуск разных версий питона под одним мастер-процессом UWSGI
1) Создание интерпретатора с опцией -fPIC для возможности компилирования uWSGI:
env PYTHON_CFLAGS=-fPIC pyenv install -v 3.6.4
pyenv virtualenv 3.6.4 prstat
2) ВАЖНО! Активация соданного интерпретатора и сборка ТОЛЬКО с помощью него.
pyenv activate prstat
3) Скачивание свежей версии исходников uWSGI
wget http://projects.unbit.it/downloads/uwsgi-latest.tar.gz
tar xf uwsgi-latest.tar.gz
cd uwsgi-2.0.17/
4) Установка пакетов для сборки с поддержкой PCRE:
apt-get install libpcre3 libpcre3-dev
5) Компиляция исполняемого файла uWSGI:
python uwsgiconfig.py --build core
mv uwsgi /home/prstat/.pyenv/versions/3.6.4/envs/prstat/bin/
6) Компиляция модуля для питона:
python uwsgiconfig.py --plugin plugins/python core python36
mv python36_plugin.so /usr/lib/uwsgi/plugins/
7) Конфигурация запуска текущим системным uWSGI нового головного процесса
собранного на нашем интерпретаторе, который будет цеплять конфиги из
специального каталога соданного для него:
cat /etc/uwsgi/apps-available/python3_prstat.ini
[uwsgi]
privileged-binary-patch-arg = /home/prstat/.pyenv/versions/3.6.4/envs/prstat/bin/uwsgi --emperor /etc/uwsgi/python3_prstat
8) Помещение симлинка на этот файл:
ln -s /etc/uwsgi/apps-available/python3_prstat.ini /etc/uwsgi/apps-enabled/python3_prstat.ini
9) Создание каталога и конфигурации:
cd /etc/uwsgi
mkdir python3_prstat
touch prstat.ini
(Содержимое prstat.ini)
[uwsgi]
plugins-dir = /usr/lib/uwsgi/plugins # Там лежит скомпилированный модуль
plugin = python36 # именно такое имя
socket = /run/uwsgi/app/python3_prstat/socket # файл должен существовать и пренадлежать www-data:www-data
processes = 1
chdir = /home/prstat/projects/prstat/ # Каталог со всем проектом
virtualenv = /home/prstat/.pyenv/versions/3.6.4/envs/prstat
uid=prstat
gid=prstat
chown-socket=www-data:www-data
env = DJANGO_SETTINGS_MODULE=prstat.settings
env = DJANGO_DEBUG=0
vacuum = True
env = IS_PRODUCTION=True # Пример того как указывается переменная окружения для проекта
env = # еще переменные если надо.
env =
env =
master = True
module = prstat.wsgi:application # это каталог "главного" апликэйшна джанко и файл wsgi внутри него.
logto = /var/log/uwsgi/app/prstat.log # Этот параметр указывает где должны быть логи самого придолжения(не эмперора который его запускает)
# логи эмперора будут скорее всего в /var/log/uwsgi/названире файла из пункта 7.
10) Конфиг nginx + ВАЖНО Не забыть сделать симлинк в sites-enabled:
root@dv03 / # cat /etc/nginx/sites-available/prstat.conf
server {
listen *:80;
server_name prstat.dv03.prural.ru;
root /home/prstat/projects/prstat;
access_log /var/log/nginx/prstat/access.log;
error_log /var/log/nginx/prstat/error.log;
location /media {
root /home/prstat/projects/prstat;
access_log off;
expires 1d;
}
location /static {
alias /home/prstat/projects/prstat/prstat/static;
access_log off;
expires 1d;
}
location / {
try_files $uri @uwsgi;
access_log off;
expires 1d;
}
location @uwsgi {
uwsgi_pass unix:///run/uwsgi/app/python3_prstat/socket;
include uwsgi_params;
}
}
----------------------------------------------------------------------------------------------------------------------------
========================== ДОПОЛНИТЕЛЬНО ОТВЕТ О ТОМ КАК ОРГАНИЗОВАТЬ ЗАПУСК ПРИЛОЖЕНИЙ=====================================
========================== ТАК ЖЕ НО БОЛЕЕ УНИВЕРСАЛЬНО В ПЛАНЕ КОНФИГУРАЦИЙ =====================================
----------------------------------------------------------------------------------------------------------------------------
https://www.digitalocean.com/community/questions/run-django-python-2-and-python-3-apps-with-uwsgi-and-nginx-on-same-server
DUMP:
You will probably have to have multiple emperor processes in this case. Usually, uWSGI is built against a particular version of Python. However, it is apparently possible to "stack" emperors so that a master emperor process can call individual Python version-specific emperor processes, which can then spawn your Django projects. I see that you've already found this StackOverflow thread on the subject.
I just tried this for the first time personally and was able to get it to work. The process is still very new to me, but I'll try to explain.
Start off by going through the tutorial as usual. For your Python 3 site, you'll want to create the virtual environment like this:
mkvirtualenv --python=/usr/bin/python3 python3projectname
If you run through the guide, you will have uWSGI built against Python 2 installed, and will be able to serve your Python 2 sites. To get the Python3 version working, you'll have to first install the development files through apt:
sudo apt-get update
sudo apt-get install python3-dev
Make a new virtual environment for the Python 3 version of uWSGI (you could just install this in your Python 3 virtual environment, but this allows for a more explicit separation so that it's obvious that it could run any number of Python 3 sites):
mkvirtualenv --python=/usr/bin/python3 python3uwsgi
Within this new virtual environment, install uWSGI. This will be built against Python 3:
pip install uwsgi
Deactivate the virtual environment when you are finished:
deactivate
The next change will be in the uWSGI structure. Since the system's uWSGI is built against Python 2, you can keep the Python 2 sites in the /etc/uwsgi/sites directory as normal. Make a new directory that will hold all of the uWSGI configs for your Python 3 sites:
sudo mkdir /etc/uwsgi/sites_python3
Move the uWSGI configurations for the Python 3 site(s) into this new directory:
sudo mv /etc/uwsgi/sites/python3projectname.ini /etc/uwsgi/sites_python3
We then need to add an additional uWSGI configuration file to the /etc/uwsgi/sites directory.
sudo nano /etc/uwsgi/sites/spawn_python3.ini
This .ini file will spawn another uWSGI emperor process, this time using the Python 3 version of uWSGI that we installed in the virtual environment. This emperor process will read the uWSGI configuration files within the /etc/uwsgi/sites_python3 directory:
/etc/uwsgi/sites/spawn_python3.ini
[uwsgi]
project = python3uwsgi
base = /home/user
privileged-binary-patch-arg = %(base)/Env/%(project)/bin/uwsgi --emperor /etc/uwsgi/sites_python3
Now, when you start the Python 2 version of uWSGI (using the upstart file from this guide), it will, in turn, spawn an additional Python 3 emperor to handle your Python 3 sites.
sudo start uwsgi
I figured this out once and validated it a second time, but it's still a completely new process for me, so take the above as a starting point. Hopefully that helps though!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment