📜 ⬆️ ⬇️

Installing a Django project on a VPS (centOS 7) [For Beginners]

I want to share practical experience in installing the finished project on Django on Reg.ru VPS. This guide is designed for beginners, it contains a number of not the best solutions, but with it you can run your project on Django for an hour.

The manual does not contain security settings. It was created on the basis of English instructions and pain, a lot of pain (links at the end of the article). The instruction is relevant for settings: centOS 7, Django 1.9.2 and Python 3.4.3

Remark: I thank Phillip Torchinsky for providing the PyCharm product version for creating a project on Django.
')

What do we have


We have a ready project on Django in the PyCharm development environment for the local computer. Those. settings.py has a sqlite3 database, broken paths to the state and an empty ALLOWED_HOSTS. This is normal.

We begin


Stage 1


We buy a domain name on the website Reg.ru. Standard procedure, nothing out of the ordinary.

We buy on Reg.ru VPS H-XEN-2 with XEN virtualization. This is necessary in order not to have problems with the kernel configuration and load distribution. We select CentOS 7 as the operating system. The tariff is rather weak, so we’ll take it to the beam than Ubuntu. Debian is not taken because it is more difficult to configure.

After purchasing a VPS, we will receive a letter with all the data. There we will be offered to link the VPS and domain. As a solution you will be offered to use the DNSAdmin control panel. However, for some reason, this thing does not work, so we skip and go to the Reg.ru control panel in the settings of your domain name.

- Your domain is DNS Servers. Set the settings according to the screenshot:



- Your domain - Zone management - add an “A” entry For example: (Ip-change to yours)



Done, we tied the domain name to the hosting. The update will take some time.

Stage 2


To work with CentOS 7, we need a program: PuTTY . Download launches and get down to work.

Primary host tuning.

To begin, we will need to add another user and assign permissions to modify the configs. This is done so that you do not break the entire system by mistake through the root-user.

1) connect via PuTTY as root and type the following commands:

- add user: adduser habrauser
adduser habrauser

- add user password: passwd habrauser
passwd habrauser

- add habrauser rights to the user: gpasswd -a habrauser wheel
gpasswd -a habrauser wheel

- disconnect from the session as root-user: exit
exit


After that we will be able to run commands by the user habrauser on behalf of the administrator through the sudo prefix

2) Connect via PuTTY under the user habrauser and type the following commands:

- Put the time zone server: sudo timedatectl set-timezone Europe/Moscow
sudo timedatectl set-timezone Europe/Moscow

- Confirm: sudo timedatectl
sudo timedatectl

- We put the time synchronizer: sudo yum install ntp
sudo yum install ntp

- Put the autorun synchronizer:
sudo systemctl start ntpd
sudo systemctl enable ntpd


Stage 3


- We put the necessary additional packages for centOS 7

sudo yum install epel-release


sudo yum install python-pip python-devel postgresql-server postgresql-devel postgresql-contrib gcc nginx


Now we can use pip to install the necessary python packages.

- We put the editor
sudo yum install nano


Customizing PostgreSQL

- Initialize PostgreSQL:

sudo postgresql-setup initdb


- We start the PostgreSQL service:

sudo systemctl start postgresql


- Open the configuration file:

sudo nano /var/lib/pgsql/data/pg_hba.conf


- Editing so that the database works with authorized users.

. . .

# TYPE DATABASE USER ADDRESS METHOD

# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
#host all all 127.0.0.1/32 ident
host all all 127.0.0.1/32 md5
# IPv6 local connections:
#host all all ::1/128 ident
host all all ::1/128 md5


To save the file, we need to press ctrl + O, then enter and yes. To exit, press ctrl + X.

- Restart service

sudo systemctl restart postgresql


- Put the autorun:

sudo systemctl enable postgresql


Creating a PostgreSQL database:

- enter the service:

sudo su - postgres


- enter the local session:

psql


- create habradb database:

CREATE DATABASE habradb;


- create a database user:

CREATE USER user WITH PASSWORD 'password';


- we give the user user rights to use the habradb database:

GRANT ALL PRIVILEGES ON DATABASE habradb TO user;


- we finish the session of working with the base:

\q


exit


Stage 4


Our project is designed to use Python3.4.3, so we will put it in a virtual environment.

- we put Python 3.4.3

sudo yum install python34-devel


- set the virtual environment:

sudo pip install virtualenv


- create the apifolder project folder in the system root (specify the name that you use in the project in PyCharm itself):

mkdir ~/apifolder


- go to this folder:

cd ~/apifolder


- we create virtual environment of djangoen with python python 3.4.3

mkvirtualenv -p /usr/bin/python3.4 djangoen


ps to correctly specify the path to python, you can use the command which python3.4
which python3.4


- we activate the virtual environment and enter it

source myprojectenv/bin/activate


- we put jungle, unicorn and base handler

pip install django gunicorn psycopg2


To install another version of django, use the command: pip install django==1.9.2 #
pip install django==1.9.2 #


Stage 5


We start to create our project Django:

- Create a Django project in the current folder (the project name is the same as mine in PyCharm):

django-admin.py startproject apifolder . # , , apifolder.


- We copy our project from the local machine.

In principle, the project should be copied from your git repository with push, but if you don’t know what git is, push and so on, then there is a more primitive way.


- Open the file settings.py and make changes to it

nano apifoldert/settings.py


Or you can change its config in the IDE, and then update it via SFTP.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql', # django 1,8 .
'NAME': 'habradb',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}

#, static , .

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (
)

# . ALLOWED_HOSTS .

DEBUG = True

ALLOWED_HOSTS = [
'*',
]


- We put the relevant packages. For example, in my case, in order for the project to support the ImageFiled model, I needed to install Pillow

sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel


pip install Pillow


- We are checking the database, we are doing the migration (Statics cannot be collected yet, since we don’t give it anything yet).

cd ~/apifolder
./manage.py makemigrations
./manage.py migrate


Sometimes these commands don't work, and you need to use: python manage.py makemigrations
python manage.py makemigrations
etc

You can also create a user

./manage.py createsuperuser


- We start the project and check its work:

./manage.py runserver 0.0.0.0:8000

The site will be available at: server_domain_or_IP : 8000

- check all points and do debugging. If at this stage you do not check all the pages, admin panel and so on, then in the future there may be many problems. Most often forgotten some little things: packages, url, local configs.

- disconnect

deactivate


Stage 6


- create Unicorn config:

sudo nano /etc/systemd/system/gunicorn.service


[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=habrauser
Group=nginx
WorkingDirectory=/home/habrauser/apifolder
ExecStart=/home/habrauser/apifolder/djangoen/bin/gunicorn --workers 3 --bind unix:/home/habrauser/apifolder/apifolder.sock apifolder.wsgi:application

[Install]
WantedBy=multi-user.target


- we start unicorn and we do it autostart:

sudo systemctl start gunicorn
sudo systemctl enable gunicorn


- We connect Nginx

sudo nano /etc/nginx/nginx.conf


sudo nano /etc/nginx/nginx.conf

We insert a new config into:

http {
. . .

include /etc/nginx/conf.d/*.conf;

#

server {
listen 80 default_server;

. . .


config itself

server {
listen 80;
server_name example.ru www.example.ru;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/habrauser/apifolder;
}

location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/home/habrauser/apifolder/apifolder.sock;
}
}


- add nginx user:

sudo usermod -a -G habrauser nginx


- we put rights:

chmod 710 /home/habrauser


- check the nginx config (should give two successful lines):

sudo nginx -t


- Put the autorun:

sudo systemctl start nginx

sudo systemctl enable nginx


Stage 7


The main part of the work is done, now we need to collect the static and restart the machine:

- go to our folder

cd ~/apifolder


- activate the environment:

source djangoen/bin/activate


- We collect statics:

./manage.py collectstatic


- we put in the file setting.py ALLOWED_HOSTS = your domain, and DEBUG = False

- reboot server: reg.ru - my hosting and services - your VPS - Reboot server

Sometimes there is not enough one time (not everything starts working as it should), so you have to load several times.

___________________________________

Starting the server www.digitalocean.com/community/tutorials/initial-server-setup-with-centos-7
Advanced settings www.digitalocean.com/community/tutorials/additional-recommended-steps-for-new-centos-7-servers
Config itself www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7

Source: https://habr.com/ru/post/277653/


All Articles