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

Want to share practical experience on the installation of the finished project in Django on VPS from Reg.ru. This guide is aimed at beginners, it contains some not the best decisions, but you will be able to run my project in Django for hours.

The user manual does not contain security settings. It was created on the basis of English-language instructions and pains, a lot of pain (links at end of article). Manual current settings: centOS 7, Django 1.9.2 and Python 3.4.3

Note: Philip Torchinsky thank you for providing a product version of PyCharm to create Django project.

the

What we have


We have a finished project in Django in a development environment, PyCharm for the local computer. Ie settings.py has a database of sqlite3, broken path to statice and empty ALLOWED_HOSTS. This is normal.

the

We start


Step 1


Buy a domain name for the website Reg.ru. Standard procedure, nothing unusual.

Buy Reg.ru H VPS-XEN-2 XEN virtualization. This is necessary in order not to have problems with the kernel configuration and load distribution. As operating system we choose CentOS 7. The rate is quite weak, so the beam to take it, rather than Ubuntu. Debian is not taken since it is more difficult to configure.

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

— Is your domain DNS Server. Set the settings according to the screenshot:



— Your domain — zone Control — add "A" record for Example: (the Ip change to your)



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

Step 2


To work with CentOS 7 we need the program: PuTTY. Download spins and get to work.

Primary setup hosting.

To begin with, we will need to add another user and assign him rights to change configs. This is to ensure that you are in error using root user didn't break the whole system.

1) connect via PuTTY using root user and type the following command:

— add user: adduser habrauser

added user password: passwd habrauser

— added user habrauser right: gpasswd-a wheel habrauser

— disconnect from the session as root user: exit


After that we will be able to run commands with user habrauser as administrator via the console sudo

2) Connect via PuTTY by user habrauser and type the following command:

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

— Confirm: sudo timedatectl

— Put the synchronizer time: sudo yum install ntp

— Set the startup synchronizer:
sudo systemctl start ntpd
sudo systemctl enable ntpd


Step 3


— 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 put the necessary Python packages.

— Set editor
sudo yum install nano


Custom PostgreSQL

— Initialize PostgreSQL:

sudo postgresql-setup initdb


— Run service PostgreSQL:

sudo systemctl start postgresql


— Open the configuration file:

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


— Editable so that the base worked 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


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

— Restart the service

sudo systemctl restart postgresql.


— Set auto start:

sudo systemctl enable postgresql


Creating PostgreSQL database:

— included in the service:

sudo su - postgres


-included in a local session:

psql


— create a database habradb:

the CREATE DATABASE habradb;


— create user database:

the CREATE USER user WITH PASSWORD 'password';


— give the user rights to the database habradb:

the GRANT ALL PRIVILEGES ON DATABASE TO user habradb;


— finish session with the database:

\q


the exit


Step 4


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

— put Python 3.4.3

sudo yum install python34-devel


— put virtual environment:

sudo pip install virtualenv


create in root of the system folder of the project apifolder (specify the name which you have used in the project in PyCharm):

mkdir ~/apifolder


— go to this folder:

cd ~/apifolder


-create virtual environment djangoen with Python python 3.4.3

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


p.s. to correctly specify the path to the Python, you can use the command which python3.4


— activate virtual environment and enter into it.

the source myprojectenv/bin/activate


— put Django, unicorn and handler database

pip install django psycopg2 gunicorn


To put a different version of django, use the command: pip install django==1.9.2 #putting the correct version


Step 5


begin to create our Django project:

— Create a Django project in the current folder (the project name is the same that is in my PyCharm):

django-admin.py startproject apifolder . # point tells us about what we put in the current folder, in this case the folder apifolder.


— Copy our project from the local machine.

The idea of the project usami need to copy from your git repository, but if you don't know what a git push and so on, that is, a more primitive method.
the
    the
  • Connect to your server via SFTP: Instrukcja
  • the
  • Open the folder home/habrauser/apifolder
  • the
  • Open your project on the local machine
  • the
  • supplemented by the Usual drag and model files the previously created project apifolder, your c project of the local machine (its name should also be apifolder, or that you specified earlier).


— Open the file settings.py and changes

nano apifoldert/settings.py


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

the DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql', # so it must be with the version of django 1.8 and above.
'NAME': 'habradb',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': ",
}
}

#Assumes you have a static folder will be in the project root and not in each separate attachment.

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

#This is useful for debugging. ALLOWED_HOSTS in the end will need to be changed to your domain.

DEBUG = True

ALLOWED_HOSTS = [
'*'
]


— Put the relevant packages. For example, in my case, the project supported the model ImageFiled, I had 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


— Check the database, do migration (Statics yet not be able to collect as we have it still gives nothing).

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


Sometimes these commands do not work, and need to use: python manage.py makemigrations
, etc.

You can also create user

./manage.py createsuperuser


— Run the project and check his work:
./manage.py runserver 0.0.0.0:8000

The site will be available at server_domain_or_IP:8000

— checkem all the points and do debugging. If at this stage not to check all pages, admin and so on, in the future may appear a lot of problems. Often forgotten some things: packages, url, local, config.

— disabled

the deactivate


Step 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


— run the unicorn and make him AutoPlay:

sudo systemctl start gunicorn
sudo systemctl enable gunicorn


— Plug-Nginx

sudo nano /etc/nginx/nginx.conf


sudo nano /etc/nginx/nginx.conf

Insert a new config in:

http {
. . .

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

#Here

server {
listen 80 default_server;

. . .


itself config

the 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 nginx habrauser


— set rights:

chmod 710 /home/habrauser


— check the nginx configuration (this should give two successful lines):

sudo nginx -t


— Set auto start:

sudo systemctl start nginx

sudo systemctl enable nginx


Step 7


Most of the work is done, now we need to gather statics and reboot the machine:

— go to the folder

cd ~/apifolder


— activate the environment:

the source djangoen/bin/activate


— Collect statics:

./manage.py collectstatic


— put in a file setting.py ALLOWED_HOSTS = your domain, and DEBUG = False

— restart the server: reg.ru my hosting and services — your VPS to Reboot the server

Sometimes once is not enough (not all starts working as it should), so you have to ship multiple times.

___________________________________

Starting the server www.digitalocean.com/community/tutorials/initial-server-setup-with-centos-7
Additional configuration www.digitalocean.com/community/tutorials/additional-recommended-steps-for-new-centos-7-servers
The config itself www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7
Article based on information from habrahabr.ru

Популярные сообщения из этого блога

Approval of WSUS updates: import, export, copy

Kaspersky Security Center — the fight for automation

The Hilbert curve vs. Z-order