current position:Home>How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04

How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04

2022-01-30 15:14:32 Top of the back end

brief introduction

Django Is a powerful network framework , Can help you Python Start an application or website .Django Includes a simplified development server , For testing your code locally , But for anything related to production , Need a safer and stronger Web The server .

Ministry office Django Applications In the traditional way It's using Web Server gateway interface (WSGI). However , With Python 3 The emergence of and support for asynchronous execution , You can now do this asynchronously Server gateway interface (ASGI) Asynchronous callable program to execute your Python Applications . As WSGI Heirs of ,Python Medium ASGI The norm is WSGI Superset , It can be used as WSGI substitute .

Django allow " External asynchronous , Internal synchronization " Pattern , Allow your code to synchronize internally , and ASGI The server processes requests asynchronously . By allowing webserver There is an asynchronous callability , It can handle multiple incoming and outgoing events for each application .Django The inside of the application is still synchronized , To allow backward compatibility , And avoid the complexity of parallel computing . It also means your Django The application can start from... Without changing WSGI Switch to ASGI.

In this guide , You will be in Ubuntu 20.04 Install and configure some components on to support and services Django Applications . You will be Set up a PostgreSQL database , Instead of using the default SQLite database . You will configure Gunicorn Application server and Uvicorn, One ASGI Realization , To connect asynchronously to your application . then , You will set Nginx As Gunicorn Reverse proxy of , Enables you to use its security and performance features to serve your applications .

Prerequisite

To complete this tutorial , You will need .

The first 1 Step - from Ubuntu Install packages in the software library

To start the process , You will Ubuntu Download and install all the items you need in the software library . Later you will use Python Package manager pip To install other components .

First , You need to update your local apt Package index , Then download and install the package . The package you install depends on which version of your project will use Python.

Use the following command to install the necessary system packages .

sudo apt update
sudo apt install python3-venv libpq-dev postgresql postgresql-contrib nginx curl
 Copy code 

This command will install the... Used to create the virtual environment Python library 、Postgres The database system and the libraries needed to interact with it , as well as Nginx Network server . Next , You will be for your Django Application creation PostgreSQL Databases and users .

The first 2 Step - establish PostgreSQL Databases and users

In this step , You will be for your Django The application creates a database and database users .

By default ,Postgres Use a method called for local connections " Peer certification " Certification scheme of . It means , If the user's operating system user name matches a valid Postgres The user name matches , The user can log in , Without further Certification .

stay Postgres During installation , Created a new one called postgres Operating system users , And postgres PostgreSQL Manage user correspondence . You will need to use this user to perform administrative tasks . You can use sudo And pass -u Option to enter the user name .

Log in to an interactive by typing Postgres conversation .

sudo -u postgres psql
 Copy code 

You will get a PostgreSQL A hint of , You can set requirements here .

First , Create a database for your project .

CREATE DATABASE myproject;
 Copy code 

** Be careful :** Every Postgres The statement must end with a semicolon . If you have problems , Make sure your command ends with a semicolon .

Next , Create a database user for the project . Make sure you choose a secure password .

CREATE USER myprojectuser WITH PASSWORD 'password';
 Copy code 

after , You need to modify some connection parameters for the user you just created . This will speed up the operation of the database , In this way, you don't have to query and set the correct value every time you establish a connection .

You will set the default encoding to UTF-8 , This is a Django What is expected . You will also set the default transaction isolation scheme to "read committed", This prevents reading data from uncommitted transactions . Last , You need to set the time zone . By default ,Django The project will be set to use UTC . These are all Django The project itself The advice of .

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';
 Copy code 

Now? , You can give your new users permission to manage the new database .

GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
 Copy code 

When you're done , Exit by typing PostgreSQL Prompt .

\q
 Copy code 

Now? Postgres It's set up , therefore Django Can connect and manage its database information .

The first 3 Step - Create a for your project Python A virtual environment

Now you have a database , You can start preparing other requirements for your project . You will install your... In a virtual environment Python demand , To facilitate management .

First , Create and move into a directory where you can save project files .

mkdir ~/myprojectdir
cd ~/myprojectdir
 Copy code 

And then use Python Built in virtual environment tools to create a new virtual environment .

python3 -m venv myprojectenv
 Copy code 

This will create a file named myprojectenv In your myprojectdir Directory . On the inside , It will install a local version of Python And a local version of pip . You can use it to install and configure an isolated for your project Python Environmental Science .

At the beginning of the installation project Python Before demand , You need to activate this virtual environment . You can do this by entering .

source myprojectenv/bin/activate
 Copy code 

Your tips should change , To show that you are now in a Python Operating in a virtual environment . It will look like this . (myprojectenv)[email protected]:~/myprojectdir$.

You will install... In a virtual environment Django. take Django Install into an environment specific to your project , Will allow your projects and their requirements to be handled separately . After your virtual environment is activated , use pip Local instance installation of Django、Gunicorn、Uvicorn and psycopg2 PostgreSQL Adapter .

** Be careful :** When the virtual environment is activated ( When your prompt is preceded by (myprojectenv) ) , Use pip instead of pip3 , Even if you use Python 3. Tool copies in virtual environments are always named pip , No matter Python How about the version of .

pip install django gunicorn uvicorn psycopg2-binary
 Copy code 

Now you should have the power to start Django All software required for the project .

Step four - Create and configure a new Django project

Installed on Python After component , You can create actual Django Project documents .

establish Django project

Because you already have a project directory , You can tell Django Install the file here . It will create a secondary directory containing the actual code , This is normal , And put a management script in this directory . The key is that you clearly define the directory , Rather than let Django Make a decision relative to your current directory .

django-admin startproject myproject ~/myprojectdir
 Copy code 

At this point , Your project directory (~/myprojectdir In this tutorial ) There should be the following .

  • ~/myprojectdir/manage.py: One Django Project management scripts .
  • ~/myprojectdir/myproject/: Django Project package . This should include __init__.py,asgi.py, settings.py ,urls.py, and wsgi.py file .
  • ~/myprojectdir/myprojectenv/: The virtual environment directory you created before .

Adjust project settings

After creating the project file , You need to adjust some settings . Open the settings file in your text editor .

nano ~/myprojectdir/myproject/settings.py
 Copy code 

First find ALLOWED_HOSTS Instructions . This defines a list of server addresses or domain names , Can be used to connect to Django example . Any with... Not in this list Host The incoming request of the header will throw an exception .Django Ask you to set this , To prevent certain types of security vulnerabilities .

In square brackets , List your Django Server related IP Address or domain name . List each item in quotation marks , The entries are separated by commas . Allow the entire domain name and any subdomain name , Please add a full stop at the beginning of the entry . In the following clip , There are several annotated examples , To demonstrate how to do this .

** Be careful :** Please ensure that the localhost As one of the options , Because you will pass the local Nginx Instance to proxy connections .

~/myprojectdir/myproject/settings.py

. . .
# The simplest case: just add the domain name(s) and IP addresses of your Django server
# ALLOWED_HOSTS = [ 'example.com', '203.0.113.5']
# To respond to 'example.com' and any subdomains, start the domain with a dot
# ALLOWED_HOSTS = ['.example.com', '203.0.113.5']
ALLOWED_HOSTS = ['your_server_domain_or_IP', 'second_domain_or_IP', . . ., 'localhost']
 Copy code 

Next , Find the part of configuring database access . It will take DATABASES Start . The configuration in this file is for SQLite Database . You have created a for your project PostgreSQL database , So you need to adjust these settings .

Use your PostgreSQL Database information change settings . You have to tell Django Use your pip Installed psycopg2 Adapter . You need to give the database name 、 Database user name 、 Password of database user , Then specify that the database is located on the local computer . You can take PORT Set to an empty string .

~/myprojectdir/myproject/settings.py

. . .

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

. . .
 Copy code 

Next , Move to the bottom of the file , Add a setting , Indicate where static files should be placed . This is necessary , In order to Nginx Able to handle requests for these items . The following line tells Django Place them in a folder called static A directory of .

~/myprojectdir/myproject/settings.py

. . .

STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
 Copy code 

When finished, save and close the file .

Complete initial project setup

Now? , You can use the management script to migrate the initial database schema to your PostgreSQL database .

~/myprojectdir/manage.py makemigrations
~/myprojectdir/manage.py migrate
 Copy code 

Create an administrative user for the project by typing .

~/myprojectdir/manage.py createsuperuser
 Copy code 

You must choose a user name , Provide an email address , And select and confirm a password .

You can collect all static content to your configured directory location by typing .

~/myprojectdir/manage.py collectstatic
 Copy code 

You will have to confirm the operation . then , Static files will be placed in your project directory under a name static A directory of .

If you follow the initial Server Setup Guide , You should have one UFW A firewall protects your server . To test the development server , You must allow access to the port you will use .

By typing 8000 Port creates an exception .

sudo ufw allow 8000
 Copy code 

Last , You can use this command to start Django Develop a server to test your project .

~/myprojectdir/manage.py runserver 0.0.0.0:8000
 Copy code 

In your web browser , Access your server's domain name or IP Address , Then input :8000 .

http://server_domain_or_IP:8000
 Copy code 

You should receive the default Django Index page .

Django index page

If you're in the address bar URL Add... At the end /admin , You will be prompted to enter your createsuperuser The administrative user name and password created by the command .

Django admin login

After certification , You can access the default Django Management interface .

Django admin interface

When you're done exploring , Click... In the terminal window CTRL+C , Shut down the development server .

test Gunicorn Ability to serve the project

In this tutorial , You will use Gunicorn And Uvicorn To deploy applications with . although Gunicorn Traditionally used to deploy WSGI Application's , But it also provides a pluggable interface to provide ASGI Deploy . It allows you to consume by ASGI The server (uvicorn ) Exposed worker classes to do this . because Gunicorn It is a more mature product , Than Uvicorn Provide more configurations ,Uvicorn Our maintainer recommends using gunicorn , And use uvicorn As a human process manager .

Before leaving the virtual environment , You have to test Gunicorn To ensure that it can serve the application .

To use uvicorn Workers and gunicorn The server , Go to your project directory , Use the following gunicorn Command to load the project ASGI modular .

cd ~/myprojectdir
gunicorn --bind 0.0.0.0:8000 myproject.asgi -w 4 -k uvicorn.workers.UvicornWorker
 Copy code 

This will be Django Start on the same interface where the development server is running Gunicorn. You can go back and test the application again .

** Be careful :** No need to use Gunicorn To run your ASGI Applications . If only uvicorn , You can use the following command .

uvicorn myproject.asgi:application --host 0.0.0.0 --port 8080
 Copy code 

** Be careful :** No styles will be applied to the management interface , because Gunicorn I don't know how to find static CSS Content .

If you start these commands ,Django The welcome page still appears , This confirms gunicorn The page was serviced , And work as expected . By using gunicorn command , You specify Django Of asgi.py The relative directory path of the file is passed to Gunicorn A module , This file is the entry to your application , Use Python Module syntax of . In this document , It's defined as application Function of , It is used to communicate with Applications . To learn more about ASGI Normative information , Please visit ASGI Official website .

When you finish the test , Click... In the terminal window CTRL+C , stop it Gunicorn.

Now you've finished the right Django Configuration of the application . You can exit the virtual environment by typing .

deactivate
 Copy code 

The virtual environment light in your prompt will be removed .

Step five - by Gunicorn establish systemd Socket And service documents

In the last section , You tested Gunicorn It can be done with Django Application interaction . In this step , You will create systemd Services and socket files to achieve a more powerful way to start and stop the application server .

Gunicorn The socket will be created at startup , And connect the monitor to . When a connection occurs ,systemd It will start automatically Gunicorn Process to handle the connection .

First , With sudo The authority of is Gunicorn Create and open one systemd Socket file .

sudo nano /etc/systemd/system/gunicorn.socket
 Copy code 

In the document , You will create a [Unit] Section to describe sockets , One [Socket] Part to define the location of the socket , One more [Install] Part to ensure that the socket is created at the right time .

/etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target
 Copy code 

When finished, save and close the file .

Next , In the text editor, type sudo The authority of is Gunicorn Create and open one systemd Service document . The name of the service file should be consistent with the socket file name of the extension .

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

from [Unit] Part of it , This section is used to specify metadata and dependencies . You have to write a description of your service here , And tell init The system only starts this service after reaching the networking goal . Because the service depends on the socket in the socket file , So you need to join a Requires Instructions to indicate this relationship .

/etc/systemd/system/gunicorn.service

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
 Copy code 

Next , open [Service] part . You will specify the users and groups of the process . You will give ownership of the process to your ordinary user account , Because it has all the relevant documents . You will hand over the ownership of the group to www-data Group , such Nginx You can easily communicate with Gunicorn signal communication .

then , You will draw the working directory , And specify the command to start the service . under these circumstances , You have to specify Gunicorn The full path to the executable , The file is already installed in the virtual environment . You will bind the process to your /run Create a directory in Unix On the socket , So that the process can communicate with Nginx signal communication . You will record all the data to standard output , In order to journald The process can collect Gunicorn journal . You can also specify any optional... Here Gunicorn adjustment . Here is an example of specifying three working processes .

/etc/systemd/system/gunicorn.service

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

[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
          --access-logfile - \
          -k uvicorn.workers.UvicornWorker \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          myproject.asgi:application
 Copy code 

Last , You want to add a [Install] part . This will tell systemd, If you let this service start at startup , Where should it be linked . You would want this service to start when a normal multi-user system starts up .

/etc/systemd/system/gunicorn.service

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

[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
          --access-logfile - \
          -k uvicorn.workers.UvicornWorker \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          myproject.asgi:application

[Install]
WantedBy=multi-user.target
 Copy code 

thus ,systemd Service file completed . Now save and close it .

Now you can start and enable Gunicorn Socket . This will be /run/gunicorn.sock , And create a socket file at startup . When a connection enters the socket ,systemd It will start automatically gunicorn.service To deal with it .

sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket
 Copy code 

Now you have established systemd Service and socket files , You will check the socket file to see if the operation was successful .

The first 6 Step - Check Gunicorn Existence of socket file

In this step , You will check Gunicorn Socket file . First , Check the status of the process , Find out if it can start .

sudo systemctl status gunicorn.socket
 Copy code 

The output will be similar .

Output● gunicorn.socket - gunicorn socket
     Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor prese>
     Active: active (listening) since Fri 2020-06-26 17:53:10 UTC; 14s ago
   Triggers: ● gunicorn.service
     Listen: /run/gunicorn.sock (Stream)
      Tasks: 0 (limit: 1137)
     Memory: 0B
     CGroup: /system.slice/gunicorn.socket
 Copy code 

Next , Check /run In the catalog gunicorn.sock Does the file exist .

file /run/gunicorn.sock
 Copy code 
Output/run/gunicorn.sock: socket
 Copy code 

If systemctl status The command indicates that an error has occurred , Or not found in the directory gunicorn.sock file , This shows that Gunicorn The socket was not created correctly . Check by typing Gunicorn Socket log .

sudo journalctl -u gunicorn.socket
 Copy code 

Take another look at your /etc/systemd/system/gunicorn.socket file , Resolve any issues before proceeding .

The first 7 Step - Test the activation of the socket

In this step , You will test the socket activation . at present , If you only start gunicorn.socket unit ,gunicorn.service Not activated yet , Because the socket hasn't received any connection yet . You can check this by typing .

sudo systemctl status gunicorn
 Copy code 
Output● gunicorn.service - gunicorn daemon
   Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
 Copy code 

To test the socket activation mechanism , You can type curl , Send a connection to the socket .

curl --unix-socket /run/gunicorn.sock localhost
 Copy code 

You should receive a message from your application in the terminal HTML Output . This shows that Gunicorn Has been started and can be used for your Django Applications provide services . You can input : To verify Gunicorn Is the service running .

sudo systemctl status gunicorn
 Copy code 
Output

● gunicorn.service - gunicorn daemon
     Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled)
     Active: active (running) since Thu 2021-06-10 21:03:29 UTC; 13s ago
TriggeredBy: ● gunicorn.socket
   Main PID: 11682 (gunicorn)
      Tasks: 4 (limit: 4682)
     Memory: 98.5M
     CGroup: /system.slice/gunicorn.service
             ├─11682 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 -k uvicorn.workers.UvicornWorker --bind unix:/run/gunicorn.sock myproject.asgi:application
             ├─11705 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 -k uvicorn.workers.UvicornWorker --bind unix:/run/gunicorn.sock myproject.asgi:application
             ├─11707 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 -k uvicorn.workers.UvicornWorker --bind unix:/run/gunicorn.sock myproject.asgi:application
             └─11708 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 -k uvicorn.workers.UvicornWorker --bind unix:/run/gunicorn.sock myproject.asgi:application

Jun 10 21:03:29 django gunicorn[11705]: [2021-06-10 21:03:29 +0000] [11705] [INFO] ASGI 'lifespan' protocol appears unsupported.
Jun 10 21:03:29 django gunicorn[11705]: [2021-06-10 21:03:29 +0000] [11705] [INFO] Application startup complete.
Jun 10 21:03:30 django gunicorn[11707]: [2021-06-10 21:03:30 +0000] [11707] [INFO] Started server process [11707]
Jun 10 21:03:30 django gunicorn[11707]: [2021-06-10 21:03:30 +0000] [11707] [INFO] Waiting for application startup.
Jun 10 21:03:30 django gunicorn[11707]: [2021-06-10 21:03:30 +0000] [11707] [INFO] ASGI 'lifespan' protocol appears unsupported.
Jun 10 21:03:30 django gunicorn[11707]: [2021-06-10 21:03:30 +0000] [11707] [INFO] Application startup complete.
Jun 10 21:03:30 django gunicorn[11708]: [2021-06-10 21:03:30 +0000] [11708] [INFO] Started server process [11708]
Jun 10 21:03:30 django gunicorn[11708]: [2021-06-10 21:03:30 +0000] [11708] [INFO] Waiting for application startup.
Jun 10 21:03:30 django gunicorn[11708]: [2021-06-10 21:03:30 +0000] [11708] [INFO] ASGI 'lifespan' protocol appears unsupported.
Jun 10 21:03:30 django gunicorn[11708]: [2021-06-10 21:03:30 +0000] [11708] [INFO] Application startup complete.


 Copy code 

If from curl The output of or systemctl status The output of indicates that a problem has occurred , Please check the log for more details .

sudo journalctl -u gunicorn
 Copy code 

Check your /etc/systemd/system/gunicorn.service Is there a problem with the file . If you are right about /etc/systemd/system/gunicorn.service The document was modified , Please reload the daemon to reread the service definition , And restart by typing Gunicorn process .

sudo systemctl daemon-reload
sudo systemctl restart gunicorn
 Copy code 

Before proceeding , Please make sure that you have eliminated the above problems .

The first 8 Step - To configure Nginx Pass to by proxy Gunicorn

Now? Gunicorn It's set up , You need to configure Nginx Pass traffic to the process . In this step , You will be in Gunicorn Front settings Nginx, To take advantage of its high-performance connection processing mechanism and easy to implement security functions .

First , stay Nginx Of sites-available Create and open a new server block in the directory .

sudo nano /etc/nginx/sites-available/myproject
 Copy code 

On the inside , Open a new server block . You will first specify that this block should listen for normal 80 port , And should respond to the server's domain name or IP Address .

/etc/nginx/sites-available/myproject

server {
    listen 80;
    server_name server_domain_or_IP;
}
 Copy code 

Next , tell Nginx Ignore any search favicon The problem of . You have to tell it , Where can I find you in ~/myprojectdir/static Static assets in the catalog . All these documents have a standard URI Prefix "/static", So you can create a location block to match these requests .

/etc/nginx/sites-available/myproject

server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/myprojectdir;
    }
}
 Copy code 

Last , Create a location / {} block , To match all other requests . In this position , You will include Nginx Standards included during installation proxy_params file , Then you will pass the traffic directly to Gunicorn Socket .

/etc/nginx/sites-available/myproject

server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/myprojectdir;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
 Copy code 

After completion , Save and close the file . Now? , You can link this file to sites-enabled Directory to enable it .

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
 Copy code 

Enter the following code , test Nginx Whether there are syntax errors in the configuration .

sudo nginx -t
 Copy code 

If no errors are reported , Continue typing and restart Nginx.

sudo systemctl restart nginx
 Copy code 

Last , You need to open the firewall , send 80 The flow of the port is normal . Because you no longer need to access the development server , You can delete open 8000 Port rules .

sudo ufw delete allow 8000
sudo ufw allow 'Nginx Full'
 Copy code 

Now you should be able to access the domain name of your server or IP Address , Look at the picture of the rocket Django The welcome page .

** Be careful :** Finish in the configuration Nginx after , The next step should be to use SSL/TLS To ensure the traffic security of the server . This is important , Because without it , All the information , Include password , They are sent through the network in plain text .

If you have a domain name , The easiest way is to use Let's Encrypt To obtain a SSL certificate , To ensure your traffic . according to This guide , stay Ubuntu 20.04 On the use of Nginx Set up Let's Encrypt. Use the... Created in this tutorial Nginx Server block , Follow this procedure .

The first 9 Step - exclude Nginx and Gunicorn Failure of

If the last step does not show your application , You will need to troubleshoot your installation .

Nginx The default page is displayed instead of Django Applications

If Nginx Show default page , Instead of proxy to your application , This usually means you need to adjust server_name Internal /etc/nginx/sites-available/myproject file , To point to your server IP Address or domain name .

Nginx Use server_name To decide which server block to use to respond to the request . If you receive Nginx The default page for , This shows that Nginx Cannot explicitly match the request to a server block , So it goes back to /etc/nginx/sites-available/default Default block defined in .

The server block in your project server_name , Must be more specific than in the default server block , To be selected .

Nginx Show 502 Bad gateway error , instead of Django Applications

502 Error indication Nginx Failed to successfully proxy request . Many configuration problems occur 502 error , Therefore, more information is needed to correct troubleshooting .

The main place to look for more information is Nginx Error log for . Generally speaking , This will tell you what conditions caused the problem in the proxy event . according to Nginx Error log for , Input .

sudo tail -F /var/log/nginx/error.log
 Copy code 

Now? , Make another request in the browser , Generate a new error ( Try refreshing the page ). You should receive a new error message written to the log . If you look at this information , It should help you narrow the scope of the problem .

You may receive the following information .

"`[secondary_label Output]
connect() to unix:/run/gunicorn.sock failed (2: No such file or directory)

OutputThis indicates that Nginx could not find the `gunicorn.sock` file at the given location. You should compare the `proxy_pass` location defined within `/etc/nginx/sites-available/myproject` file to the actual location of the `gunicorn.sock` file generated by the `gunicorn.socket` systemd unit.

If you cannot find a `gunicorn.sock` file within the `/run` directory, it generally means that the systemd socket file was unable to create it. Go back to the [section on checking for the Gunicorn socket file](#checking-for-the-gunicorn-socket-file) to step through the troubleshooting steps for Gunicorn.

```
connect() to unix:/run/gunicorn.sock failed (13: Permission denied)
 Copy code 

This shows that Nginx Unable to connect to... Due to permission problems Gunicorn Socket . When the program uses root instead of sudo When users , This could happen . although systemd Be able to create Gunicorn Socket file , but Nginx But you can't access it .

If in the root directory (/) and gunicorn.sock There are limited permissions at any point between files , That's what happens . You can pass the absolute path of the socket file to namei command , To view the permissions and ownership values of the socket file and each of its parent directories .

namei -l /run/gunicorn.sock
 Copy code 
Outputf: /run/gunicorn.sock
drwxr-xr-x root root /
drwxr-xr-x root root run
srw-rw-rw- root root gunicorn.sock
 Copy code 

The output shows the permissions of each directory component . By viewing permissions ( First column )、 owner ( Second column ) And group owners ( The third column ), You can find out what permission is for socket What kind of access to files .

In the example above , The socket file and every directory leading to the socket file have read and execute permissions ( The permission bar of the directory is marked with r-x ending , instead of --- ). Nginx The process should be able to successfully access the socket .

If any directory leading to the socket does not have read and execute permissions ,Nginx The socket will not be accessible , Unless the world is allowed to read and execute , Or ensure that ownership of the group is given to Nginx Group to which .

Django Show :"could not connect to server: Connection rejected "

When you try to access parts of an application in a web browser , You may start from Django Received a message .

"`[secondary_label Output]
OperationalError at /admin/login/
could not connect to server: Connection rejected
Whether the server is on the host "localhost"(127.0.0.1) Up operation , and
stay 5432 Port accept TCP/IP Connect ?


This indicates that Django is unable to connect to the Postgres database.  Make sure that the Postgres instance is running by typing:

```command
sudo systemctl status postgresql
 Copy code 

If not , You can start it , And make it start automatically at startup by typing ( If it hasn't been configured like this ).

sudo systemctl start postgresql
sudo systemctl enable postgresql
 Copy code 

If you still have problems , Make sure ~/myprojectdir/myproject/settings.py The database settings defined in the file are correct .

Further troubleshooting

For additional troubleshooting , Logs can help narrow the root cause . Check each of them in turn , Look for information that indicates the problem area .

The following logs may be helpful .

  • Check by typing Nginx Process log .sudo journalctl -u nginx
  • Check by typing Nginx Access log .sudo less /var/log/nginx/access.log
  • Check by typing Nginx Error log for .sudo less /var/log/nginx/error.log
  • Check by typing Gunicorn Log of the application .sudo journalctl -u gunicorn
  • Check by typing Gunicorn Socket log .sudo journalctl -u gunicorn.socket

When you update your configuration or application , You may need to restart these processes , To adapt to your changes .

If you update your Django Applications , You can restart by typing Gunicorn Process to receive these changes .

sudo systemctl restart gunicorn
 Copy code 

If you change Gunicorn Socket or service file , Please reload the daemon , And restart the process by typing .

sudo systemctl daemon-reload
sudo systemctl restart gunicorn.socket gunicorn.service
 Copy code 

If you change Nginx Configuration of server block , Test configuration , Then type Nginx.

sudo nginx -t && sudo systemctl restart nginx
 Copy code 

These commands help you catch changes as you adjust your configuration .

summary

In this guide , You've set up a... In your virtual environment ASGI Django project . You configured Gunicorn and Uvicorn To asynchronously translate client requests , In order to Django Be able to handle them . after , You set up. Nginx Act as a reverse proxy to handle client connections , And provide the correct project according to the client request .

Django Simplifies the process of creating projects and Applications , Provides many common parts , Enables you to focus on unique elements . By using the general tool chain described in this paper , You can serve the application you create from a server .

copyright notice
author[Top of the back end],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301514197389.html

Random recommended