Django è un framework Web gratuito, open source e di alto livello utilizzato per lo sviluppo di applicazioni Web Python. Viene fornito con una serie di strumenti che consentono di creare applicazioni Web sicure e scalabili. Il suo obiettivo principale è facilitare la creazione di applicazioni complesse e si occupa della struttura interna.
In questo tutorial impareremo come installare Django e configurare Nginx come proxy inverso per Django su CentOS 8.
Prerequisiti
- Un server che esegue CentOS 8.
- Sul tuo server è configurata una password di root.
Installa i pacchetti richiesti
Django è un framework basato su Python, quindi dovrai installare Python e PIP nel tuo sistema. Puoi installarli eseguendo il seguente comando:
dnf install python36 python3-pip -y
Una volta installati entrambi i pacchetti, puoi procedere al passaggio successivo.
Installa Django
Puoi installare Django con il comando PIP come mostrato di seguito:
pip3 install Django
Dopo aver installato Django, puoi controllare la versione di Django con il seguente comando:
django-admin --version
Dovresti vedere la versione di Django nel seguente output:
3.0.3
Crea un progetto Django
A questo punto, Django è installato. Ora è il momento di creare una nuova applicazione Django.
Puoi creare una nuova applicazione Django usando il comando django-admin all'interno della directory /opt come mostrato di seguito:
cd /opt
django-admin startproject djangoproject
Una volta creato il progetto django, cambia la directory in djangoproject e migra le modifiche con il seguente comando:
cd djangoproject
python3 manage.py migrate
Dovresti ottenere il seguente output:
Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK
Successivamente, dovrai creare un account utente amministratore per gestire il progetto Django. Puoi crearlo con il seguente comando:
python3 manage.py createsuperuser
Ti verrà chiesto di fornire il tuo nome utente, email e password. Puoi fornirli secondo la tua scelta come mostrato di seguito:
Username (leave blank to use 'root'): dadmin Email address: [email protected] Password: Password (again): Superuser created successfully.
Una volta terminato, puoi procedere al passaggio successivo.
Avvia l'applicazione Django
Per impostazione predefinita, non è possibile accedere all'applicazione Django dagli host remoti. Quindi dovrai consentire Django per host esterni. Puoi farlo aggiungendo l'IP del tuo server in settings.py:
nano /opt/djangoproject/djangoproject/settings.py
Modifica la seguente riga:
ALLOWED_HOSTS = ['your-server-ip']
Salva e chiudi il file. Quindi, avvia l'applicazione Django con il seguente comando:
cd /opt/djangoproject
python3 manage.py runserver 0.0.0.0:8000
Dovresti vedere il seguente output:
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 03, 2020 - 02:31:19 Django version 3.0.3, using settings 'djangoproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Django application is now started and runs on port 8000.
A questo punto, l'applicazione Django è ora avviata e viene eseguita sulla porta 8000. Ora puoi procedere al passaggio successivo.
Configura SELinux e Firewall
Successivamente, dovrai consentire le porte 8000 e 80 tramite firewalld. Puoi consentirli con il seguente comando:
firewall-cmd --permanent --add-port=8000/tcp
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload
Quindi, configura SELinux con il seguente comando:
setsebool httpd_can_network_connect on -P
Una volta terminato, puoi procedere al passaggio successivo.
Accedi all'applicazione Django
Puoi accedere all'applicazione Django visitando l'URL http://your-server-ip:8000. Dovresti vedere la seguente pagina:
Puoi anche accedere all'interfaccia di amministrazione di Django utilizzando l'URL http://your-server-ip:8000/admin. Dovresti vedere la seguente pagina:
Fornisci il nome utente e la password dell'amministratore e fai clic sul Registro dentro pulsante. Dovresti vedere la seguente pagina:
Installa Nginx e Gunicorn
In questa sezione, installeremo Gunicorn per creare e gestire il servizio Django e Nginx per servire l'applicazione Django.
Innanzitutto, installa Nginx con il seguente comando:
dnf install nginx -y
Quindi, installa Gunicorn usando il comando PIP come mostrato di seguito:
pip3 install gunicorn
Una volta installati entrambi i pacchetti, avvia il servizio Nginx e abilitalo all'avvio dopo il riavvio del sistema con il seguente comando:
systemctl start nginx
systemctl enable nginx
Quindi, cambia la proprietà della directory /opt/djangoproject in Nginx come mostrato di seguito:
chown -R nginx:nginx /opt/djangoproject
Crea un file di servizio Systemd per Django
Quindi, crea un file di servizio systemd per la gestione del servizio Django con il seguente comando:
nano /etc/systemd/system/django.service
Aggiungi le seguenti righe:
[Unit] Description=django daemon After=network.target [Service] User=nginx Group=nginx WorkingDirectory=/opt/djangoproject ExecStart=/usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:application [Install] WantedBy=multi-user.target
Salva e chiudi il file, quindi ricarica il demone systemd con il seguente comando:
systemctl daemon-reload
Quindi, avvia il servizio Django e abilitalo all'avvio dopo il riavvio del sistema con il seguente comando:
systemctl start django
systemctl enable django
Ora puoi controllare lo stato del servizio Django con il seguente comando:
systemctl status django
Dovresti vedere il seguente output:
? django.service - django daemon Loaded: loaded (/etc/systemd/system/django.service; disabled; vendor preset: disabled) Active: active (running) since Mon 2020-03-02 22:27:51 EST; 3min 32s ago Main PID: 960 (django) Tasks: 4 (limit: 25028) Memory: 95.2M CGroup: /system.slice/django.service ??960 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a> ??964 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a> ??965 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a> ??966 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a> Mar 02 22:27:51 centos8 systemd[1]: Started django daemon. Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [960] [INFO] Starting django 20.0.4 Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [960] [INFO] Listening at: unix:/opt/djangoproject/djangoproject.sock (960) Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [960] [INFO] Using worker: sync Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [964] [INFO] Booting worker with pid: 964 Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [965] [INFO] Booting worker with pid: 965 Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [966] [INFO] Booting worker with pid: 966 h pid: 966
Configura Nginx per Django
Successivamente, dovrai configurare Nginx come proxy inverso per Django. Per farlo, crea un nuovo file di configurazione Nginx con il seguente comando:
nano /etc/nginx/conf.d/django.conf
Aggiungi le seguenti righe:
server { listen 80; server_name your-server-ip location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /opt/djangoproject; } 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:/opt/djangoproject/djangoproject.sock; } }
Salva e chiudi il file quando hai finito. Quindi, verifica nginx per eventuali errori di sintassi con il seguente comando:
nginx -t
Se tutto va bene, dovresti ottenere il seguente output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Quindi, riavvia il servizio Nginx per implementare le modifiche:
systemctl start nginx
Puoi anche verificare Nginx con il seguente comando:
systemctl status nginx
Dovresti ottenere il seguente output:
? nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled) Active: active (running) since Mon 2020-03-02 22:28:13 EST; 4min 14s ago Process: 984 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS) Process: 982 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Process: 980 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS) Main PID: 985 (nginx) Tasks: 3 (limit: 25028) Memory: 5.5M CGroup: /system.slice/nginx.service ??985 nginx: master process /usr/sbin/nginx ??986 nginx: worker process ??987 nginx: worker process Mar 02 22:28:12 centos8 systemd[1]: Starting The nginx HTTP and reverse proxy server... Mar 02 22:28:12 centos8 nginx[982]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok Mar 02 22:28:12 centos8 nginx[982]: nginx: configuration file /etc/nginx/nginx.conf test is successful Mar 02 22:28:13 centos8 systemd[1]: Started The nginx HTTP and reverse proxy server.
Ora puoi accedere alla tua applicazione Django utilizzando l'URL http://your-server-ip.
Conclusione
In questa guida abbiamo appreso come installare Django su CentOS 8. Abbiamo anche imparato come utilizzare Gunicorn per creare e gestire il servizio Django e configurare Nginx come proxy inverso per servire l'applicazione Django.