Evgenii Legotckoi
Evgenii LegotckoiSept. 16, 2016, 1:56 p.m.

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Once access to the server with Ubuntu 16.04 was set in a previous article, it is time to expand on it everything necessary for operation of the site, namely:

  • Django
  • framework for developing web-applications in Python;
  • PostgreSQL
  • SQL database;
  • Gunicorn - WSGI HTTP Python server for UNIX systems;
  • Ngnix - HTTP-server and a reverse proxy server, mail proxy server and TCP/UDP general purpose proxy;
  • Supervisor - This process manager, which greatly simplifies the management of long-running programs, such as sites that you want to automatically restart after a fall.

Step 1 - system upgrade

Let us update existing packages. You never know, the system is obsolete packages.

sudo apt-get update
sudo apt-get upgrade

Step 2 - Install all the required packages without installing a virtual environment

Establish a bundle of all the packages that will not be used by virtualenv, namely Python 3, PostgreSQL, Nginx.

sudo apt-get install python3-dev python3-setuptools libpq-dev postgresql postgresql-contrib nginx

Pip I eventually installed separately through easy_install3 utility that comes bundled python3-setuptools , firstly because then put the latest version, and secondly in the case of installation through apt-get are errors when installing packages virtualenv.

sudo easy_install3 pip

Step 3 - Creating a database and a user database

And now create the database and user database, giving extended rights postgres user via the sudo utility, which is created when you install PostgreSQL.

sudo -u postgres psql

After completing this command, we get to PostgreSQL console, where we will create the necessary database and user on whose behalf the Django app will connect to the database.

Create database:

CREATE DATABASE myproject;

Create user:

CREATE USER myprojectuser WITH PASSWORD 'password';

Next, the user configuration of the project. Encoding it will use UTF8, because this encoding is used in the Django, a Python files recommends hardcoding encoded UTF8, especially if they present the text to be displayed on the site. Also set the isolation level in a database. That is, when the data will be available for reading. In this case, after the transaction is in the general case. Of course, there are cases where the data is available to confirm, but it's a different story. And also set the type of time zones that the default Django UTC.

ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myprojectuser SET timezone TO 'UTC';

Next, give the right of access to the database for the user:

GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

Exit from PostgreSQL console.

\q

Step 4 - Installing the virtual environment

Install and activate the virtual environment:

pip3 install virtualenv
virtualenv ~/myprojectenv
source myprojectenv/bin/activate

Step 5 -Installation of PostgreSQL driver

The installation with the following command

sudo pip install django psycopg2 

Inside the virtual environment, you must use the pip command, not pip3

Step 6 - Project creating

Let's move to a folder with a virtual environment, we still have to be in operation in a virtual environment. And create a project.

cd ~/myprojectenv
django-admin.py startproject myproject

Step 7 - Setting up the database connection

Now, edit the configuration file the Django, it connects to a PostgreSQL database, but not create and further connected to the SQLite database.

nano ~/myproject/myproject/settings.py

To do this, locate the following piece of code file:

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   }
}

...

And replace it with the following, taking into account your data to connect to the database:

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myproject',
        'USER': 'myprojectuser',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

...

Step 8 - Perform database migration

Django has one very big advantage - it has built-in admin panel that very easy life. But to make it work, you must perform a database migration, that is, to prepare a model of the SQL data queries that form the structure of the database.

cd ~/myproject
python manage.py makemigrations
python manage.py migrate

And even create a superuser who is the administrator with the highest access rights to your site. Run the following command and follow the instructions.

python manage.py createsuperuser

Step 9 - Install Gunicorn

Establish Gunicorn, which will act as an HTTP server for our website. Set it inside a virtual environment.

sudo pip install django gunicorn

You can verify that the site is already running:

gunicorn myproject.wsgi:application --bind 111.222.333.44:8000  # Your IP-address

Step 10 - Configuring static files

Django by default gives static files only in Debug mode, which is not used to combat the server. To combat all server static files of all projects going in a separate folder with a special collectstatic command, and the folder itself must be specified in the settings.py file.

Edit it:

nano ~/myproject/settings.py

And add a line that will indicate where to collect static files.

STATIC_ROOT = '/home/user/myprojectenv/myproject/myproject/static/'

And now will collect all statics files in this catalog:

python manage.py collectstatic

Step 11 - Configuring Nginx

Edit the Nginx configuration file.

sudo nano /etc/nginx/sites-available/default

We remove all the contents and replaced with the following.

server {
    listen 80;
    server_name 111.222.333.44; # your ip-address
    access_log  /var/log/nginx/example.log;

    location /static/ {
        root /home/user/myprojectenv/myproject/myproject/;
        expires 30d;
    }

    location / {
        proxy_pass http://127.0.0.1:8000; 
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Restart Nginx.

sudo service nginx restart

Start gunicorn

gunicorn myproject.wsgi:application

After that, you will find that the site is already available on port 80.

Step 12 - Configuring supervisor

To ensure that the site is accessible at any time of the day, you must configure-supervisor, which hangs in the memory as a service and will make sure that the site has always worked.

sudo apt-get install supervisor

For stable operation Gunicorn need to create its configuration file. It will be located next to the file, which will run for our web-application.

cd /home/user/myprojectenv/myproject/myproject
touch gunicorn.conf.py
nano gunicorn.conf.py

Add the following configuration information:

bind = '127.0.0.1:8000'
workers = 3
user = "nobody"

That is, we specify which port is bound and which user starts the process. As well as the number of working processes. In this case, three. It is calculated by the following formula:

workers = Ncpu + 1

Then create a configuration of supervisor

cd /etc/supervisor/conf.d/
touch myproject.conf
nano myproject.conf

The following settings prescribe it

[program:myproject]
command=/home/user/myprojectenv/bin/gunicorn myproject.wsgi:application -c /home/user/myprojectenv/myproject/myproject/gunicorn.conf.py
directory=/home/user/myprojectenv/myproject
user=nobody
autorestart=true
redirect_stderr=true

Now run the supervisor. There is a caveat installation supervisor. It is not as start his service after having been installed. Therefore it is necessary to force to add it to startup and run manually if you do not want to restart the server.

sudo update-rc.d supervisor enable
sudo service supervisor start

Well, then you can update the config files, check the status of the application site, and restart them.

supervisorctl reread
supervisorctl update
supervisorctl status myproject
supervisor restart myproject

When the server reboots everything will start automatically

Notes

If you change the project files, you will need to restart gunicorn. To do this, activate the virtual environment is enough to use killall command

source ~/myprojectenv/bin/activate
sudo killall gunicorn

Supervisor automatically start Gunicorn after this command, so you can not worry that the server will fall for a long time. Not a second failure.

For Django I recommend VDS-server of Timeweb hoster
.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

A
  • Oct. 28, 2017, 9:30 a.m.

С чем может быть связана ошибка? ставил всё на свою машину, статический ip не покупал.
(myprojectenv) ubuntu@ubuntu:~/myprojectenv/myproject$ gunicorn myproject.wsgi:application --bind мойайпишник:8000
[2017-10-28 11:54:39 +0000] [31426] [INFO] Starting gunicorn 19.7.1
[2017-10-28 11:54:39 +0000] [31426] [ERROR] Invalid address: ('мойайпишник', 8000)
[2017-10-28 11:54:39 +0000] [31426] [ERROR] Retrying in 1 second.
[2017-10-28 11:54:40 +0000] [31426] [ERROR] Invalid address: ('мойайпишник', 8000)
[2017-10-28 11:54:40 +0000] [31426] [ERROR] Retrying in 1 second.
[2017-10-28 11:54:41 +0000] [31426] [ERROR] Invalid address: ('мойайпишник', 8000)
[2017-10-28 11:54:41 +0000] [31426] [ERROR] Retrying in 1 second.
[2017-10-28 11:54:42 +0000] [31426] [ERROR] Invalid address: ('мойайпишник', 8000)
[2017-10-28 11:54:42 +0000] [31426] [ERROR] Retrying in 1 second.
[2017-10-28 11:54:43 +0000] [31426] [ERROR] Invalid address: ('мойайпишник', 8000)
[2017-10-28 11:54:43 +0000] [31426] [ERROR] Retrying in 1 second.
[2017-10-28 11:54:44 +0000] [31426] [ERROR] Can't connect to ('мойайпишник', 8000)

Evgenii Legotckoi
  • Oct. 28, 2017, 9:55 a.m.

Этот ваш IP адрес случайно не внешний IP адрес роутера, за которым Вы сидите со своим ПК?

A
  • Oct. 28, 2017, 10:15 a.m.

перепробывал все ip, которые нашёл у себя на компе. не подскажите, как найти нужный?

Evgenii Legotckoi
  • Oct. 28, 2017, 10:21 a.m.

А Вы делали вообще bind на '127.0.0.1:8000'?

то есть
bind = '127.0.0.1:8000'
gunicorn слушает порт на внутренней петле
b
  • Aug. 24, 2018, 2:56 a.m.
sudo pip install django gunicorn

sudo pip install django psycopg2





По моему sudo здесь лишнее. Разве sudo устанавливает внутри виртуального окружения?
Evgenii Legotckoi
  • Aug. 24, 2018, 3 a.m.

Как ни странно - Да.

Илья Чичак
  • Dec. 11, 2018, 9:25 a.m.

Некропост, однако, хотел бы добавить, что в случае с продакшеном, миграции там делать нельзя. (точнее, конечно, можно, но нельзя)

Все миграции необходимо хранить в репозитории.

Evgenii Legotckoi
  • Dec. 11, 2018, 9:28 a.m.

Твоя правда. Согласен. Свои миграции храню в репозитории. На продакшене только выполняю обновление структуры базы данных, после тестирования на дев сервере конечно (читай локальная машина разработки).

S
  • June 25, 2020, 2:02 p.m.

Здравствуйте, подскажите пожалуйста, как исправить:
в Ubuntu 20.04, в каталоге проекта пытаюсь создать вертуальную среду
virtualenv env
вылезает ошибка:
ModuleNotFoundError: No module named 'virtualenv.seed.via_app_data'
Спасибо.

Evgenii Legotckoi
  • June 25, 2020, 2:40 p.m.

Это может быть и ошибка в вашей версии virtualenv и не совсем верная установка, и косяки в процессе следования туториалу.
Но подобные ошибки вылезали на GitHub в репозитории virtualenv.
Впрочем я сам с таким не сталкивался, так что готового ответа у меня нет.

Илья Чичак
  • June 25, 2020, 3:24 p.m.
  • (edited)

Установите venv:

sudo apt install python3-venv

после этого можно сделать

python -m venv .venv
source .venv/bin/activate

virtualenv - устаревший, venv - часть стандартной библиотеки. в Windows - venv ставится вместе с питоном, в убунте, к сожалению, даже куски стандартной библиотеки приходится доставлять руками.

S
  • June 25, 2020, 3:37 p.m.

Ок, спасибо, буду пробовать.

S
  • June 25, 2020, 3:56 p.m.

Все заработало, немного ругнулся, что лучше:
python3 -m venv .venv
но в итоге все сработало.
Спасибо!

АМ
  • Dec. 20, 2020, 11:45 a.m.

Стави все по статье. Добрался до шага 12 и после него перестал запускатся сервер через gunicorn myproject.wsgi:application. выдает ошибку
[ERROR] Exception in worker process
Traceback (most recent call last):
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/wo rkers/base.py", line 119, in init_process
self.load_wsgi()
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
self.wsgi = self.app.wsgi()
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
return self.load_wsgiapp()
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
return util.import_app(self.app_uri)
File "/home/user/myproject/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app
mod = importlib.import_module(module)
File "/usr/lib/python3.8/importlib/ init .py", line 127, in import _module
return _bootstrap._gcd_import(name[level:], package, level)
File " ", line 1014, in _gcd_import
File " ", line 991, in _find_and_load
File " ", line 973, in _find_and_load_un locked
ModuleNotFoundError: No module named 'myproject.wsgi'

На что обратить внимание?

После команд запуска supervisor'а

sudo update-rc.d supervisor enable
sudo service supervisor start

нужно ли вообще в виртуальном окружении запускать Gunicorn

Илья Чичак
  • Dec. 20, 2020, 12:47 p.m.

я думаю, вам стоит кастовать сюда Евгения - я предпочитаю использовать systemd для запуска и менеджмента сервера

попробуйте призвать его через кнопку ответить

АМ
  • Dec. 20, 2020, 2:09 p.m.

Евгений доброй ночи, можете что-то посоветовать?

Илья Чичак
  • Dec. 20, 2020, 8:01 p.m.

привет
тут нужна твоя помощь=)
я в супервизоре - ноль=)

Alexander
  • Jan. 20, 2021, 3:40 p.m.

Ошибка в конфиге инжинкса про статику в root последний слеш лишний путь в таком виде получается

/home/user/myprojectenv/myproject/myproject//static
IscanderChe
  • Feb. 18, 2021, 5:32 a.m.

На продакшене только выполняю обновление структуры базы данных

День добрый.
А как вы это делаете?

Илья Чичак
  • Feb. 18, 2021, 5:39 a.m.

python manage.py migrate

IscanderChe
  • Feb. 18, 2021, 6:07 a.m.

А разве это не миграция? И как тогда быть с вашим утверждением о миграциях:

в случае с продакшеном, миграции там делать нельзя. (точнее, конечно, можно, но нельзя)

Илья Чичак
  • Feb. 18, 2021, 6:19 a.m.

я имел в виду, что на проде нельзя делать

python manage.py makemigrations

правильнее было бы сказать, что на проде нельзя создавать миграции. мигрировать БД - без этого, естественно, никак

IscanderChe
  • Feb. 18, 2021, 6:25 a.m.

Всё, теперь понял. Спасибо!

IscanderChe
  • Feb. 18, 2021, 9:04 a.m.

Ещё вопрос: как правильно обновлять кодовую базу, если произошли изменения в ней?

Илья Чичак
  • Feb. 18, 2021, 10:18 a.m.
  • (edited)

обновлять где?
если на проде -

git pull && python manage.py migrate && python manage.py collectstatic --noinput && sudo systemctl service restart && sudo service nginx restart

если вы используете systemd для управления сервером

IscanderChe
  • Feb. 18, 2021, 11:14 a.m.

То есть я правильно понимаю, что на боевом сервере нужно ставить помимо всего ещё и git?

Илья Чичак
  • Feb. 18, 2021, 11:51 a.m.
  • (edited)

в целом, тут все не просто

в зависимости от способа доставки это может быть k8s, docker, rsync, ansible, git... да хоть wget-ом качать архив с условного гитхаба

и для каждого способа свои способы доставки и развертывания

для начала, если у вас 1 сервер и минимум каких-то особенностей, git pull вполне хватит. И да, для этого нужно, чтобы был git установлен

IscanderChe
  • Feb. 18, 2021, 12:04 p.m.

Ясно. Спасибо за развёрнутый ответ.

Думаю, что мне для моих целей хватит и git. Локально я им пользоваться умею, а вот с удалёнными серверами не сталкивался, только с github, отсюда и вопросы.

IscanderChe
  • Feb. 20, 2021, 12:17 p.m.

Сижу, ковыряюсь с git pull на виртуалке, и ни черта не понимаю.

Как правильно залить проект на удалённый сервер, чтобы он по git pull принимал изменения? Отправить изменения с локальной машины у меня получилось, а вот на git pull ругается:

There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=<remote>/<branch> master
IscanderChe
  • Feb. 20, 2021, 3:39 p.m.

Всё, разобрался.

IscanderChe
  • Feb. 21, 2021, 3:17 a.m.

В виртуальном окружении ругается на отсутствие pip:

sudo: pip: command not found

pip ставил вот так:

sudo apt-get install python3-pip

поскольку easy_install3 почему-то не поставился вместе с setuptools.

Илья Чичак
  • Feb. 21, 2021, 10:55 a.m.

в виртуальном окружении не надо использовать sudo

используя sudo вы ставите пакеты глобально. Если у вас один проект на сервере - ок. но если нет, все плюсы от venv-ов идут на смарку.
кстати, советую посмотреть в сторону poetry - на мой взгялд, это проект уже production-ready. пакеты ставятся в несколько потоков, фиксируются не только зависимости, но и зависимости зависимостей. А venv-вы создаются автоматически и не в проекте. может быть не очень удобно, но можно переопределить поведение локально и глобально. в целом, советую

IscanderChe
  • Feb. 21, 2021, 1:18 p.m.

Ага, спасибо, завелось!

Да мне бы хотя бы с основами разобраться, куда уж продвинутые уровни...

IscanderChe
  • Feb. 22, 2021, 3:14 a.m.
  • (edited)

На шаге 11 вылезла вот такая ошибка:

DisallowedHost at /
Invalid HTTP_HOST header: '10.0.3.15'. You may need to add '10.0.3.15' to ALLOWED_HOSTS

Проблема решилась добавлением в settings.py в ALLOWED_HOSTS IP-адреса 10.0.3.15.

IscanderChe
  • Feb. 22, 2021, 3:44 a.m.

После шага 12 сайт вместо стартовой страницы Django показывает: "502 Bad Gateway".

Что не так?

Илья Чичак
  • Feb. 22, 2021, 5 a.m.

покажите конфиг nginx и ка запускаете gunicorn

IscanderChe
  • Feb. 22, 2021, 5:07 a.m.
  • (edited)

Всё по мануалу выше, буква в букву.

gunicorn mysite.wsgi:application
server {
        listen 80;
        server_name 10.0.3.15;
        access_log /var/log/nginx/example.log;

        location /static/ {
                root /home/django/.env/mysite/mysite/;
                expires 30d;
        }

        location / {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header Host $server_name;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}
IscanderChe
  • Feb. 22, 2021, 5:08 a.m.

Всё по мануалу выше, буква в букву.

gunicorn mysite.wsgi:application
server {
        listen 80;
        server_name 10.0.3.15;
        access_log /var/log/nginx/example.log;

        location /static/ {
                root /home/django/.env/mysite/mysite/;
                expires 30d;
        }

        location / {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header Host $server_name;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}
Илья Чичак
  • Feb. 22, 2021, 9:09 a.m.

нужна твоя помощь=)

IscanderChe
  • Feb. 23, 2021, 1:15 p.m.

Поднял сервис с помощью systemd, вот по этому мануалу: https://habr.com/ru/post/501414/

D
  • March 2, 2021, 3 a.m.

А почему нельзя? Где можно об этом почитать? Киньте, пожалуйста, в меня ссылкой.

L
  • May 29, 2021, 9:44 p.m.

При любых попытках взаимодействовать с супервизаром, выбивает в такую ошибку

error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/local/lib/python3.8/dist-packages/supervisor/xmlrpc.py line: 560

Помогите пожалуйста, уже все волосы выдрал

D
  • May 30, 2021, 12:12 p.m.

Это на какую команду так отвечает?

L
  • May 30, 2021, 1:18 p.m.

Отвечал на все команды после

sudo service supervisor start

Исправил таким образом

sudo killall supervisord
sudo supervisord -c /etc/supervisor/supervisord.conf

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks