One place for hosting & domains

      Postgres

      How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 20.04


      Not using Ubuntu 20.04?


      Choose a different version or distribution.

      Introduction

      Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a more secure and powerful web server is required.

      In this guide, we will demonstrate how to install and configure some components on Ubuntu 20.04 to support and serve Django applications. We will be setting up a PostgreSQL database instead of using the default SQLite database. We will configure the Gunicorn application server to interface with our applications. We will then set up Nginx to reverse proxy to Gunicorn, giving us access to its security and performance features to serve our apps.

      Prerequisites and Goals

      In order to complete this guide, you should have a fresh Ubuntu 20.04 server instance with a basic firewall and a non-root user with sudo privileges configured. You can learn how to set this up by running through our initial server setup guide.

      We will be installing Django within a virtual environment. Installing Django into an environment specific to your project will allow your projects and their requirements to be handled separately.

      Once we have our database and application up and running, we will install and configure the Gunicorn application server. This will serve as an interface to our application, translating client requests from HTTP to Python calls that our application can process. We will then set up Nginx in front of Gunicorn to take advantage of its high performance connection handling mechanisms and its easy-to-implement security features.

      Let’s get started.

      Installing the Packages from the Ubuntu Repositories

      To begin the process, we’ll download and install all of the items we need from the Ubuntu repositories. We will use the Python package manager pip to install additional components a bit later.

      We need to update the local apt package index and then download and install the packages. The packages we install depend on which version of Python your project will use.

      If you are using Django with Python 3, type:

      • sudo apt update
      • sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl

      Django 1.11 is the last release of Django that will support Python 2. If you are starting new projects, it is strongly recommended that you choose Python 3. If you still need to use Python 2, type:

      • sudo apt update
      • sudo apt install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx curl

      This will install pip, the Python development files needed to build Gunicorn later, the Postgres database system and the libraries needed to interact with it, and the Nginx web server.

      Creating the PostgreSQL Database and User

      We’re going to jump right in and create a database and database user for our Django application.

      By default, Postgres uses an authentication scheme called “peer authentication” for local connections. Basically, this means that if the user’s operating system username matches a valid Postgres username, that user can login with no further authentication.

      During the Postgres installation, an operating system user named postgres was created to correspond to the postgres PostgreSQL administrative user. We need to use this user to perform administrative tasks. We can use sudo and pass in the username with the -u option.

      Log into an interactive Postgres session by typing:

      You will be given a PostgreSQL prompt where we can set up our requirements.

      First, create a database for your project:

      • CREATE DATABASE myproject;

      Note: Every Postgres statement must end with a semi-colon, so make sure that your command ends with one if you are experiencing issues.

      Next, create a database user for our project. Make sure to select a secure password:

      • CREATE USER myprojectuser WITH PASSWORD 'password';

      Afterwards, we’ll modify a few of the connection parameters for the user we just created. This will speed up database operations so that the correct values do not have to be queried and set each time a connection is established.

      We are setting the default encoding to UTF-8, which Django expects. We are also setting the default transaction isolation scheme to “read committed”, which blocks reads from uncommitted transactions. Lastly, we are setting the timezone. By default, our Django projects will be set to use UTC. These are all recommendations from the Django project itself:

      • 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';

      Now, we can give our new user access to administer our new database:

      • GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

      When you are finished, exit out of the PostgreSQL prompt by typing:

      Postgres is now set up so that Django can connect to and manage its database information.

      Creating a Python Virtual Environment for your Project

      Now that we have our database, we can begin getting the rest of our project requirements ready. We will be installing our Python requirements within a virtual environment for easier management.

      To do this, we first need access to the virtualenv command. We can install this with pip.

      If you are using Python 3, upgrade pip and install the package by typing:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      If you are using Python 2, upgrade pip and install the package by typing:

      • sudo -H pip install --upgrade pip
      • sudo -H pip install virtualenv

      With virtualenv installed, we can start forming our project. Create and move into a directory where we can keep our project files:

      • mkdir ~/myprojectdir
      • cd ~/myprojectdir

      Within the project directory, create a Python virtual environment by typing:

      This will create a directory called myprojectenv within your myprojectdir directory. Inside, it will install a local version of Python and a local version of pip. We can use this to install and configure an isolated Python environment for our project.

      Before we install our project’s Python requirements, we need to activate the virtual environment. You can do that by typing:

      • source myprojectenv/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (myprojectenv)user@host:~/myprojectdir$.

      With your virtual environment active, install Django, Gunicorn, and the psycopg2 PostgreSQL adaptor with the local instance of pip:

      Note: When the virtual environment is activated (when your prompt has (myprojectenv) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip, regardless of the Python version.

      • pip install django gunicorn psycopg2-binary

      You should now have all of the software needed to start a Django project.

      Creating and Configuring a New Django Project

      With our Python components installed, we can create the actual Django project files.

      Creating the Django Project

      Since we already have a project directory, we will tell Django to install the files here. It will create a second level directory with the actual code, which is normal, and place a management script in this directory. The key to this is that we are defining the directory explicitly instead of allowing Django to make decisions relative to our current directory:

      • django-admin.py startproject myproject ~/myprojectdir

      At this point, your project directory (~/myprojectdir in our case) should have the following content:

      • ~/myprojectdir/manage.py: A Django project management script.
      • ~/myprojectdir/myproject/: The Django project package. This should contain the __init__.py, settings.py, urls.py, asgi.py, and wsgi.py files.
      • ~/myprojectdir/myprojectenv/: The virtual environment directory we created earlier.

      Adjusting the Project Settings

      The first thing we should do with our newly created project files is adjust the settings. Open the settings file in your text editor:

      • nano ~/myprojectdir/myproject/settings.py

      Start by locating the ALLOWED_HOSTS directive. This defines a list of the server’s addresses or domain names may be used to connect to the Django instance. Any incoming requests with a Host header that is not in this list will raise an exception. Django requires that you set this to prevent a certain class of security vulnerability.

      In the square brackets, list the IP addresses or domain names that are associated with your Django server. Each item should be listed in quotations with entries separated by a comma. If you wish requests for an entire domain and any subdomains, prepend a period to the beginning of the entry. In the snippet below, there are a few commented out examples used to demonstrate:

      Note: Be sure to include localhost as one of the options since we will be proxying connections through a local Nginx instance.

      ~/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']
      

      Next, find the section that configures database access. It will start with DATABASES. The configuration in the file is for a SQLite database. We already created a PostgreSQL database for our project, so we need to adjust the settings.

      Change the settings with your PostgreSQL database information. We tell Django to use the psycopg2 adaptor we installed with pip. We need to give the database name, the database username, the database user’s password, and then specify that the database is located on the local computer. You can leave the PORT setting as an empty string:

      ~/myprojectdir/myproject/settings.py

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

      Next, move down to the bottom of the file and add a setting indicating where the static files should be placed. This is necessary so that Nginx can handle requests for these items. The following line tells Django to place them in a directory called static in the base project directory:

      ~/myprojectdir/myproject/settings.py

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

      Save and close the file when you are finished.

      Completing Initial Project Setup

      Now, we can migrate the initial database schema to our PostgreSQL database using the management script:

      • ~/myprojectdir/manage.py makemigrations
      • ~/myprojectdir/manage.py migrate

      Create an administrative user for the project by typing:

      • ~/myprojectdir/manage.py createsuperuser

      You will have to select a username, provide an email address, and choose and confirm a password.

      We can collect all of the static content into the directory location we configured by typing:

      • ~/myprojectdir/manage.py collectstatic

      You will have to confirm the operation. The static files will then be placed in a directory called static within your project directory.

      If you followed the initial server setup guide, you should have a UFW firewall protecting your server. In order to test the development server, we’ll have to allow access to the port we’ll be using.

      Create an exception for port 8000 by typing:

      Finally, you can test our your project by starting up the Django development server with this command:

      • ~/myprojectdir/manage.py runserver 0.0.0.0:8000

      In your web browser, visit your server’s domain name or IP address followed by :8000:

      http://server_domain_or_IP:8000
      

      You should receive the default Django index page:

      Django index page

      If you append /admin to the end of the URL in the address bar, you will be prompted for the administrative username and password you created with the createsuperuser command:

      Django admin login

      After authenticating, you can access the default Django admin interface:

      Django admin interface

      When you are finished exploring, hit CTRL-C in the terminal window to shut down the development server.

      Testing Gunicorn’s Ability to Serve the Project

      The last thing we want to do before leaving our virtual environment is test Gunicorn to make sure that it can serve the application. We can do this by entering our project directory and using gunicorn to load the project’s WSGI module:

      • cd ~/myprojectdir
      • gunicorn --bind 0.0.0.0:8000 myproject.wsgi

      This will start Gunicorn on the same interface that the Django development server was running on. You can go back and test the app again.

      Note: The admin interface will not have any of the styling applied since Gunicorn does not know how to find the static CSS content responsible for this.

      We passed Gunicorn a module by specifying the relative directory path to Django’s wsgi.py file, which is the entry point to our application, using Python’s module syntax. Inside of this file, a function called application is defined, which is used to communicate with the application. To learn more about the WSGI specification, click here.

      When you are finished testing, hit CTRL-C in the terminal window to stop Gunicorn.

      We’re now finished configuring our Django application. We can back out of our virtual environment by typing:

      The virtual environment indicator in your prompt will be removed.

      Creating systemd Socket and Service Files for Gunicorn

      We have tested that Gunicorn can interact with our Django application, but we should implement a more robust way of starting and stopping the application server. To accomplish this, we’ll make systemd service and socket files.

      The Gunicorn socket will be created at boot and will listen for connections. When a connection occurs, systemd will automatically start the Gunicorn process to handle the connection.

      Start by creating and opening a systemd socket file for Gunicorn with sudo privileges:

      • sudo nano /etc/systemd/system/gunicorn.socket

      Inside, we will create a [Unit] section to describe the socket, a [Socket] section to define the socket location, and an [Install] section to make sure 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
      

      Save and close the file when you are finished.

      Next, create and open a systemd service file for Gunicorn with sudo privileges in your text editor. The service filename should match the socket filename with the exception of the extension:

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

      Start with the [Unit] section, which is used to specify metadata and dependencies. We’ll put a description of our service here and tell the init system to only start this after the networking target has been reached. Because our service relies on the socket from the socket file, we need to include a Requires directive to indicate that relationship:

      /etc/systemd/system/gunicorn.service

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

      Next, we’ll open up the [Service] section. We’ll specify the user and group that we want to process to run under. We will give our regular user account ownership of the process since it owns all of the relevant files. We’ll give group ownership to the www-data group so that Nginx can communicate easily with Gunicorn.

      We’ll then map out the working directory and specify the command to use to start the service. In this case, we’ll have to specify the full path to the Gunicorn executable, which is installed within our virtual environment. We will bind the process to the Unix socket we created within the /run directory so that the process can communicate with Nginx. We log all data to standard output so that the journald process can collect the Gunicorn logs. We can also specify any optional Gunicorn tweaks here. For example, we specified 3 worker processes in this case:

      /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 - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 
                myproject.wsgi:application
      

      Finally, we’ll add an [Install] section. This will tell systemd what to link this service to if we enable it to start at boot. We want this service to start when the regular multi-user system is up and running:

      /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 - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 
                myproject.wsgi:application
      
      [Install]
      WantedBy=multi-user.target
      

      With that, our systemd service file is complete. Save and close it now.

      We can now start and enable the Gunicorn socket. This will create the socket file at /run/gunicorn.sock now and at boot. When a connection is made to that socket, systemd will automatically start the gunicorn.service to handle it:

      • sudo systemctl start gunicorn.socket
      • sudo systemctl enable gunicorn.socket

      We can confirm that the operation was successful by checking for the socket file.

      Checking for the Gunicorn Socket File

      Check the status of the process to find out whether it was able to start:

      • sudo systemctl status gunicorn.socket

      You should receive an output like this:

      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

      Next, check for the existence of the gunicorn.sock file within the /run directory:

      Output

      /run/gunicorn.sock: socket

      If the systemctl status command indicated that an error occurred or if you do not find the gunicorn.sock file in the directory, it’s an indication that the Gunicorn socket was not able to be created correctly. Check the Gunicorn socket’s logs by typing:

      • sudo journalctl -u gunicorn.socket

      Take another look at your /etc/systemd/system/gunicorn.socket file to fix any problems before continuing.

      Testing Socket Activation

      Currently, if you’ve only started the gunicorn.socket unit, the gunicorn.service will not be active yet since the socket has not yet received any connections. You can check this by typing:

      • sudo systemctl status gunicorn

      Output

      ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: inactive (dead)

      To test the socket activation mechanism, we can send a connection to the socket through curl by typing:

      • curl --unix-socket /run/gunicorn.sock localhost

      You should receive the HTML output from your application in the terminal. This indicates that Gunicorn was started and was able to serve your Django application. You can verify that the Gunicorn service is running by typing:

      • sudo systemctl status gunicorn

      Output

      ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: active (running) since Fri 2020-06-26 18:52:21 UTC; 2s ago TriggeredBy: ● gunicorn.socket Main PID: 22914 (gunicorn) Tasks: 4 (limit: 1137) Memory: 89.1M CGroup: /system.slice/gunicorn.service ├─22914 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico> ├─22927 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico> ├─22928 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico> └─22929 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico> Jun 26 18:52:21 django-tutorial systemd[1]: Started gunicorn daemon. Jun 26 18:52:21 django-tutorial gunicorn[22914]: [2020-06-26 18:52:21 +0000] [22914] [INFO] Starting gunicorn 20.0.4 Jun 26 18:52:21 django-tutorial gunicorn[22914]: [2020-06-26 18:52:21 +0000] [22914] [INFO] Listening at: unix:/run/gunicorn.sock (22914) Jun 26 18:52:21 django-tutorial gunicorn[22914]: [2020-06-26 18:52:21 +0000] [22914] [INFO] Using worker: sync Jun 26 18:52:21 django-tutorial gunicorn[22927]: [2020-06-26 18:52:21 +0000] [22927] [INFO] Booting worker with pid: 22927 Jun 26 18:52:21 django-tutorial gunicorn[22928]: [2020-06-26 18:52:21 +0000] [22928] [INFO] Booting worker with pid: 22928 Jun 26 18:52:21 django-tutorial gunicorn[22929]: [2020-06-26 18:52:21 +0000] [22929] [INFO] Booting worker with pid: 22929

      If the output from curl or the output of systemctl status indicates that a problem occurred, check the logs for additional details:

      • sudo journalctl -u gunicorn

      Check your /etc/systemd/system/gunicorn.service file for problems. If you make changes to the /etc/systemd/system/gunicorn.service file, reload the daemon to reread the service definition and restart the Gunicorn process by typing:

      • sudo systemctl daemon-reload
      • sudo systemctl restart gunicorn

      Make sure you troubleshoot the above issues before continuing.

      Configure Nginx to Proxy Pass to Gunicorn

      Now that Gunicorn is set up, we need to configure Nginx to pass traffic to the process.

      Start by creating and opening a new server block in Nginx’s sites-available directory:

      • sudo nano /etc/nginx/sites-available/myproject

      Inside, open up a new server block. We will start by specifying that this block should listen on the normal port 80 and that it should respond to our server’s domain name or IP address:

      /etc/nginx/sites-available/myproject

      server {
          listen 80;
          server_name server_domain_or_IP;
      }
      

      Next, we will tell Nginx to ignore any problems with finding a favicon. We will also tell it where to find the static assets that we collected in our ~/myprojectdir/static directory. All of these files have a standard URI prefix of “/static”, so we can create a location block to match those 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;
          }
      }
      

      Finally, we’ll create a location / {} block to match all other requests. Inside of this location, we’ll include the standard proxy_params file included with the Nginx installation and then we will pass the traffic directly to the 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;
          }
      }
      

      Save and close the file when you are finished. Now, we can enable the file by linking it to the sites-enabled directory:

      • sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

      Test your Nginx configuration for syntax errors by typing:

      If no errors are reported, go ahead and restart Nginx by typing:

      • sudo systemctl restart nginx

      Finally, we need to open up our firewall to normal traffic on port 80. Since we no longer need access to the development server, we can remove the rule to open port 8000 as well:

      • sudo ufw delete allow 8000
      • sudo ufw allow 'Nginx Full'

      You should now be able to go to your server’s domain or IP address to view your application.

      Note: After configuring Nginx, the next step should be securing traffic to the server using SSL/TLS. This is important because without it, all information, including passwords are sent over the network in plain text.

      If you have a domain name, the easiest way to get an SSL certificate to secure your traffic is using Let’s Encrypt. Follow this guide to set up Let’s Encrypt with Nginx on Ubuntu 20.04. Follow the procedure using the Nginx server block we created in this guide.

      Troubleshooting Nginx and Gunicorn

      If this last step does not show your application, you will need to troubleshoot your installation.

      Nginx Is Showing the Default Page Instead of the Django Application

      If Nginx displays the default page instead of proxying to your application, it usually means that you need to adjust the server_name within the /etc/nginx/sites-available/myproject file to point to your server’s IP address or domain name.

      Nginx uses the server_name to determine which server block to use to respond to requests. If you receive the default Nginx page, it is a sign that Nginx wasn’t able to match the request to a sever block explicitly, so it’s falling back on the default block defined in /etc/nginx/sites-available/default.

      The server_name in your project’s server block must be more specific than the one in the default server block to be selected.

      Nginx Is Displaying a 502 Bad Gateway Error Instead of the Django Application

      A 502 error indicates that Nginx is unable to successfully proxy the request. A wide range of configuration problems express themselves with a 502 error, so more information is required to troubleshoot properly.

      The primary place to look for more information is in Nginx’s error logs. Generally, this will tell you what conditions caused problems during the proxying event. Follow the Nginx error logs by typing:

      • sudo tail -F /var/log/nginx/error.log

      Now, make another request in your browser to generate a fresh error (try refreshing the page). You should receive a fresh error message written to the log. If you look at the message, it should help you narrow down the problem.

      You might receive the following message:

      connect() to unix:/run/gunicorn.sock failed (2: No such file or directory)

      This indicates that Nginx was unable to 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 to step through the troubleshooting steps for Gunicorn.

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

      This indicates that Nginx was unable to connect to the Gunicorn socket because of permissions problems. This can happen when the procedure is followed using the root user instead of a sudo user. While systemd is able to create the Gunicorn socket file, Nginx is unable to access it.

      This can happen if there are limited permissions at any point between the root directory (/) the gunicorn.sock file. We can review the permissions and ownership values of the socket file and each of its parent directories by passing the absolute path to our socket file to the namei command:

      • namei -l /run/gunicorn.sock

      Output

      f: /run/gunicorn.sock drwxr-xr-x root root / drwxr-xr-x root root run srw-rw-rw- root root gunicorn.sock

      The output displays the permissions of each of the directory components. By looking at the permissions (first column), owner (second column) and group owner (third column), we can figure out what type of access is allowed to the socket file.

      In the above example, the socket file and each of the directories leading up to the socket file have world read and execute permissions (the permissions column for the directories end with r-x instead of ---). The Nginx process should be able to access the socket successfully.

      If any of the directories leading up to the socket do not have world read and execute permission, Nginx will not be able to access the socket without allowing world read and execute permissions or making sure group ownership is given to a group that Nginx is a part of.

      Django Is Displaying: “could not connect to server: Connection refused”

      One message that you may receive from Django when attempting to access parts of the application in the web browser is:

      OperationalError at /admin/login/
      could not connect to server: Connection refused
          Is the server running on host "localhost" (127.0.0.1) and accepting
          TCP/IP connections on port 5432?
      

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

      • sudo systemctl status postgresql

      If it is not, you can start it and enable it to start automatically at boot (if it is not already configured to do so) by typing:

      • sudo systemctl start postgresql
      • sudo systemctl enable postgresql

      If you are still having issues, make sure the database settings defined in the ~/myprojectdir/myproject/settings.py file are correct.

      Further Troubleshooting

      For additional troubleshooting, the logs can help narrow down root causes. Check each of them in turn and look for messages indicating problem areas.

      The following logs may be helpful:

      • Check the Nginx process logs by typing: sudo journalctl -u nginx
      • Check the Nginx access logs by typing: sudo less /var/log/nginx/access.log
      • Check the Nginx error logs by typing: sudo less /var/log/nginx/error.log
      • Check the Gunicorn application logs by typing: sudo journalctl -u gunicorn
      • Check the Gunicorn socket logs by typing: sudo journalctl -u gunicorn.socket

      As you update your configuration or application, you will likely need to restart the processes to adjust to your changes.

      If you update your Django application, you can restart the Gunicorn process to pick up the changes by typing:

      • sudo systemctl restart gunicorn

      If you change Gunicorn socket or service files, reload the daemon and restart the process by typing:

      • sudo systemctl daemon-reload
      • sudo systemctl restart gunicorn.socket gunicorn.service

      If you change the Nginx server block configuration, test the configuration and then Nginx by typing:

      • sudo nginx -t && sudo systemctl restart nginx

      These commands are helpful for picking up changes as you adjust your configuration.

      Conclusion

      In this guide, we’ve set up a Django project in its own virtual environment. We’ve configured Gunicorn to translate client requests so that Django can handle them. Afterwards, we set up Nginx to act as a reverse proxy to handle client connections and serve the correct project depending on the client request.

      Django makes creating projects and applications simple by providing many of the common pieces, allowing you to focus on the unique elements. By leveraging the general tool chain described in this article, you can easily serve the applications you create from a single server.



      Source link

      Настройка Django с Postgres, Nginx и Gunicorn в Ubuntu 18.04


      Введение

      Django — это мощная веб-система, помогающая создать приложение или сайт Python с нуля. Django включает упрощенный сервер разработки для локального тестирования кода, однако для серьезных производственных задач требуется более защищенный и мощный веб-сервер.

      В этом руководстве мы покажем, как установить и настроить определенные компоненты Ubuntu 18.04 для поддержки и обслуживания приложений Django. Вначале мы создадим базу данных PostgreSQL вместо того, чтобы использовать базу данных по умолчанию SQLite. Мы настроим сервер приложений Gunicorn для взаимодействия с нашими приложениями. Затем мы настроим Nginx для работы в качестве обратного прокси-сервера Gunicorn, что даст нам доступ к функциям безопасности и повышения производительности для обслуживания наших приложений.

      Предварительные требования и цели

      Для прохождения этого обучающего модуля вам потребуется новый экземпляр сервера Ubuntu 18.04 с базовым брандмауэром и пользователем с привилегиями sudo и без привилегий root. Чтобы узнать, как настроить такой сервер, воспользуйтесь нашим модулем Руководство по начальной настройке сервера.

      Мы будем устанавливать Django в виртуальной среде. Установка Django в отдельную среду проекта позволит отдельно обрабатывать проекты и их требования.

      Когда база данных будет работать, мы выполним установку и настройку сервера приложений Gunicorn. Он послужит интерфейсом нашего приложения и будет обеспечивать преобразование запросов клиентов по протоколу HTTP в вызовы Python, которые наше приложение сможет обрабатывать. Затем мы настроим Nginx в качестве обратного прокси-сервера для Gunicorn, чтобы воспользоваться высокоэффективными механизмами обработки соединений и удобными функциями безопасности.

      Давайте приступим.

      Установка пакетов из хранилищ Ubuntu

      Чтобы начать данную процедуру нужно загрузить и установить все необходимые нам элементы из хранилищ Ubuntu. Для установки дополнительных компонентов мы немного позднее используем диспетчер пакетов Python pip.

      Нам нужно обновить локальный индекс пакетов apt, а затем загрузить и установить пакеты. Конкретный состав устанавливаемых пакетов зависит от того, какая версия Python будет использоваться в вашем проекте.

      Если вы используете Django с Python 3, введите:

      • sudo apt update
      • sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl

      Версия Django 1.11 — последняя версия Django с поддержкой Python 2. Если вы создаете новый проект, мы настоятельно рекомендуем использовать Python 3. Если вам необходимо использовать Python 2, введите:

      • sudo apt update
      • sudo apt install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx curl

      Эта команда устанавливает pip, файлы разработки Python для последующего построения сервера Gunicorn, СУБД Postgres и необходимые для взаимодействия с ней библиотеки, а также веб-сервер Nginx.

      Создание базы данных и пользователя PostgreSQL

      Вначале мы создадим базу данных и пользователя базы данных для нашего приложения Django.

      По умолчанию Postgres использует для локальных соединений схему аутентификации «peer authentication». Это означает, что если имя пользователя операционной системы совпадает с действительным именем пользователя Postgres, этот пользователь может войти без дополнительной аутентификации.

      Во время установки Postgres был создан пользователь операционной системы с именем postgres, соответствующий пользователю postgres базы данных PostgreSQL, имеющему права администратора. Этот пользователь нам потребуется для выполнения административных задач. Мы можем использовать sudo и передать это имя пользователя с опцией -u.

      Выполните вход в интерактивный сеанс Postgres, введя следующую команду:

      Вы увидите диалог PostgreSQL, где можно будет задать наши требования.

      Вначале создайте базу данных для своего проекта:

      • CREATE DATABASE myproject;

      Примечание. Каждое выражение Postgres должно заканчиваться точкой с запятой. Если с вашей командой возникнут проблемы, проверьте это.

      Затем создайте пользователя базы данных для нашего проекта. Обязательно выберите безопасный пароль:

      • CREATE USER myprojectuser WITH PASSWORD 'password';

      Затем мы изменим несколько параметров подключения для только что созданного нами пользователя. Это ускорит работу базы данных, поскольку теперь при каждом подключении не нужно будет запрашивать и устанавливать корректные значения.

      Мы зададим кодировку по умолчанию UTF-8, чего и ожидает Django. Также мы зададим схему изоляции транзакций по умолчанию «read committed», которая будет блокировать чтение со стороны неподтвержденных транзакций. В заключение мы зададим часовой пояс. По умолчанию наши проекты Django настроены на использование времени по Гринвичу (UTC). Все эти рекомендации взяты из проекта Django:

      • 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';

      Теперь мы предоставим созданному пользователю доступ для администрирования новой базы данных:

      • GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

      Завершив настройку, закройте диалог PostgreSQL с помощью следующей команды:

      Теперь настройка Postgres завершена, и Django может подключаться к базе данных и управлять своей информацией в базе данных.

      Создание виртуальной среды Python для вашего проекта

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

      Для этого нам потребуется доступ к команде virtualenv. Для установки мы можем использовать pip.

      Если вы используете Python 3, обновите pip и установите пакет с помощью следующей команды:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      Если вы используете Python 2, обновите pip и установите пакет с помощью следующей команды:

      • sudo -H pip install --upgrade pip
      • sudo -H pip install virtualenv

      После установки virtualenv мы можем начать формирование нашего проекта. Создайте каталог для файлов нашего проекта и перейдите в этот каталог:

      • mkdir ~/myprojectdir
      • cd ~/myprojectdir

      Создайте в каталоге проекта виртуальную среду Python с помощью следующей команды:

      Эта команда создаст каталог myprojectenv в каталоге myprojectdir. В этот каталог будут установлены локальная версия Python и локальная версия pip. Мы можем использовать эту команду для установки и настройки изолированной среды Python для нашего проекта.

      Прежде чем установить требования Python для нашего проекта, необходимо активировать виртуальную среду. Для этого можно использовать следующую команду:

      • source myprojectenv/bin/activate

      Командная строка изменится, показывая, что теперь вы работаете в виртуальной среде Python. Она будет выглядеть примерно следующим образом: (myprojectenv)user@host:~/myprojectdir$.

      После запуска виртуальной среды установите Django, Gunicorn и адаптер psycopg2 PostgreSQL с помощью локального экземпляра pip:

      Примечание. Если виртуальная среда активна (когда перед командной строкой стоит (myprojectenv)), необходимо использовать pip вместо pip3, даже если вы используете Python 3. Копия инструмента в виртуальной среде всегда имеет имя pip вне зависимости от версии Python.

      • pip install django gunicorn psycopg2-binary

      Теперь у вас должно быть установлено все программное обеспечение, необходимое для запуска проекта Django.

      Создание и настройка нового проекта Django

      Установив компоненты Python, мы можем создать реальные файлы проекта Django.

      Создание проекта Django

      Поскольку у нас уже есть каталог проекта, мы укажем Django установить файлы в него. В этом каталоге будет создан каталог второго уровня с фактическим кодом (это нормально) и размещен скрипт управления. Здесь мы явно определяем каталог, а не даем Django принимать решения относительно текущего каталога:

      • django-admin.py startproject myproject ~/myprojectdir

      Сейчас каталог вашего проекта (в нашем случае ~/myprojectdir) должен содержать следующее:

      • ~/myprojectdir/manage.py: скрипт управления проектами Django.
      • ~/myprojectdir/myproject/: пакет проекта Django. В нем должны содержаться файлы __init__.py, settings.py, urls.py и wsgi.py.
      • ~/myprojectdir/myprojectenv/: виртуальный каталог, которы мы создали до этого.

      Изменение настроек проекта

      Прежде всего, необходимо изменить настройки созданных файлов проекта. Откройте файл настроек в текстовом редакторе:

      • nano ~/myprojectdir/myproject/settings.py

      Найдите директиву ALLOWED_HOSTS. Она определяет список адресов сервера или доменных имен, которые можно использовать для подключения к экземпляру Django. Любой входящий запрос с заголовком Host, не включенный в этот список, будет вызывать исключение. Django требует, чтобы вы использовали эту настройку, чтобы предотвратить использование определенного класса уязвимости безопасности.

      В квадратных скобках перечислите IP-адреса или доменные имена, связанные с вашим сервером Django. Каждый элемент должен быть указан в кавычках, отдельные записи должны быть разделены запятой. Если вы хотите включить в запрос весь домен и любые субдомены, добавьте точку перед началом записи. В следующем фрагменте кода для демонстрации в строках комментариев приведено несколько примеров:

      Примечание. Обязательно используйте localhost как одну из опций, поскольку мы будем использовать локальный экземпляр Nginx как прокси-сервер.

      ~/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']
      

      Затем найдите раздел. который будет настраивать доступ к базе данных. Он будет начинаться со слова DATABASES. Конфигурация в файле предназначена для базы данных SQLite. Мы уже создали базу данных PostgreSQL для нашего проекта, и поэтому нужно изменить настройки.

      Измените настройки, указав параметры базы данных PostgreSQL. Мы укажем Django использовать адаптер psycopg2, который мы установили вместе с pip. Нам нужно указать имя базы данных, имя пользователя базы данных, пароль пользователя базы данных, и указать, что база данных расположена на локальном компьютере. Вы можете оставить для параметра PORT пустую строку:

      ~/myprojectdir/myproject/settings.py

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

      Затем перейдите в конец файла и добавьте параметр, указывающий, где следует разместить статичные файлы. Это необходимо, чтобы Nginx мог обрабатывать запросы для этих элементов. Следующая строка указывает Django, что они помещаются в каталог static в базовом каталоге проекта:

      ~/myprojectdir/myproject/settings.py

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

      Сохраните файл и закройте его после завершения.

      Завершение начальной настройки проекта

      Теперь мы можем перенести начальную схему базы данных для нашей базы данных PostgreSQL, используя скрипт управления:

      • ~/myprojectdir/manage.py makemigrations
      • ~/myprojectdir/manage.py migrate

      Создайте административного пользователя проекта с помощью следующей команды:

      • ~/myprojectdir/manage.py createsuperuser

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

      Мы можем собрать весь статичный контент в заданном каталоге с помощью следующей команды:

      • ~/myprojectdir/manage.py collectstatic

      Данную операцию нужно будет подтвердить. Статичные файлы будут помещены в каталог static в каталоге вашего проекта.

      Если вы следовали указаниям модуля по начальной настройке сервера, ваш сервер должен защищать брандмауэр UFW. Чтобы протестировать сервер разработки, необходимо разрешить доступ к порту, который мы будем использовать.

      Создайте исключение для порта 8000 с помощью следующей команды:

      Теперь вы можете протестировать ваш проект, запустив сервер разработки Django с помощью следующей команды:

      • ~/myprojectdir/manage.py runserver 0.0.0.0:8000

      Откройте в браузере доменное имя или IP-адрес вашего сервера с суффиксом :8000:

      http://server_domain_or_IP:8000
      

      Вы увидите страницу индекса Django по умолчанию:

      Страница индекса Django

      Если вы добавите /admin в конце URL в панели адреса, вам будет предложено ввести имя пользователя и пароль администратора, созданные с помощью команды createsuperuser:

      Вход в панель администратора Django

      После аутентификации вы получите доступ к интерфейсу администрирования Django по умолчанию:

      Интерфейс администрирования Django

      Завершив изучение, нажмите CTRL+C в окне терминала, чтобы завершить работу сервера разработки.

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

      Перед выходом из виртуальной среды нужно протестировать способность Gunicorn обслуживать приложение. Для этого нам нужно войти в каталог нашего проекта и использовать gunicorn для загрузки модуля WSGI проекта:

      • cd ~/myprojectdir
      • gunicorn --bind 0.0.0.0:8000 myproject.wsgi

      Gunicorn будет запущен на том же интерфейсе, на котором работал сервер разработки Django. Теперь вы можете вернуться и снова протестировать приложение.

      Примечание. В интерфейсе администратора не будут применяться в стили, поскольку Gunicorn неизвестно, как находить требуемый статичный контент CSS.

      Мы передали модуль в Gunicorn, указав относительный путь к файлу Django wsgi.py, который представляет собой точку входа в наше приложение. Для этого мы использовали синтаксис модуля Python. В этом файле определена функция application, которая используется для взаимодействия с приложением. Дополнительную информацию о спецификации WSGI можно найти здесь.

      После завершения тестирования нажмите CTRL+C в окне терминала, чтобы остановить работу Gunicorn.

      Мы завершили настройку нашего приложения Django. Теперь мы можем выйти из виртуальной среды с помощью следующей команды:

      Индикатор виртуальной среды будет убран из командной строки.

      Создание файлов сокета и служебных файлов systemd для Gunicorn

      Мы убедились, что Gunicorn может взаимодействовать с нашим приложением Django, но теперь нам нужно реализовать более надежный способ запуска и остановки сервера приложений. Для этого мы создадим служебные файлы и файлы сокета systemd.

      Сокет Gunicorn создается при загрузке и прослушивает подключения. При подключении systemd автоматически запускает процесс Gunicorn для обработки подключения.

      Создайте и откройте файл сокета systemd для Gunicorn с привилегиями sudo:

      • sudo nano /etc/systemd/system/gunicorn.socket

      В этом файле мы создадим раздел [Unit] для описания сокета, раздел [Socket] для определения расположения сокета и раздел [Install], чтобы обеспечить установку сокета в нужное время:

      /etc/systemd/system/gunicorn.socket

      [Unit]
      Description=gunicorn socket
      
      [Socket]
      ListenStream=/run/gunicorn.sock
      
      [Install]
      WantedBy=sockets.target
      

      Сохраните файл и закройте его после завершения.

      Теперь создайте и откройте служебный файл systemd для Gunicorn в текстовом редакторе с привилегиями sudo. Имя файла службы должно соответствовать имени файла сокета за исключением расширения:

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

      Начните с раздела [Unit], предназначенного для указания метаданных и зависимостей. Здесь мы разместим описание службы и предпишем системе инициализации запускать ее только после достижения сетевой цели: Поскольку наша служба использует сокет из файла сокета, нам потребуется директива Requires, чтобы задать это отношение:

      /etc/systemd/system/gunicorn.service

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

      Теперь откроем раздел [Service]. Здесь указываются пользователь и группа, от имени которых мы хотим запустить данный процесс. Мы сделаем владельцем процесса учетную запись обычного пользователя, поскольку этот пользователь является владельцем всех соответствующих файлов. Групповым владельцем мы сделаем группу www-data, чтобы Nginx мог легко взаимодействовать с Gunicorn.

      Затем мы составим карту рабочего каталога и зададим команду для запуска службы. В данном случае мы укажем полный путь к исполняемому файлу Gunicorn, установленному в нашей виртуальной среде. Мы привяжем процесс к сокету Unix, созданному в каталоге /run, чтобы процесс мог взаимодействовать с Nginx. Мы будем регистрировать все данные на стандартном выводе, чтобы процесс journald мог собирать журналы Gunicorn. Также здесь можно указать любые необязательные настройки Gunicorn. Например, в данном случае мы задали 3 рабочих процесса:

      /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 - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 
                myproject.wsgi:application
      

      Наконец, добавим раздел [Install]. Это покажет systemd, куда привязывать эту службу, если мы активируем ее запуск при загрузке. Нам нужно, чтобы эта служба запускалась во время работы обычной многопользовательской системы:

      /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 - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 
                myproject.wsgi:application
      
      [Install]
      WantedBy=multi-user.target
      

      Теперь служебный файл systemd готов. Сохраните и закройте его.

      Теперь мы можем запустить и активировать сокет Gunicorn. Файл сокета /run/gunicorn.sock будет создан сейчас и будет создаваться при загрузке. При подключении к этому сокету systemd автоматически запустит gunicorn.service для его обработки:

      • sudo systemctl start gunicorn.socket
      • sudo systemctl enable gunicorn.socket

      Успешность операции можно подтвердить, проверив файл сокета.

      Проверка файла сокета Gunicorn

      Проверьте состояние процесса, чтобы узнать, удалось ли его запустить:

      • sudo systemctl status gunicorn.socket

      Затем проверьте наличие файла gunicorn.sock в каталоге /run:

      Output

      /run/gunicorn.sock: socket

      Если команда systemctl status указывает на ошибку, или если в каталоге отсутствует файл gunicorn.sock, это означает, что сокет Gunicorn не удалось создать. Проверьте журналы сокета Gunicorn с помощью следующей команды:

      • sudo journalctl -u gunicorn.socket

      Еще раз проверьте файл /etc/systemd/system/gunicorn.socket и устраните любые обнаруженные проблемы, прежде чем продолжить.

      Тестирование активации сокета

      Если вы запустили только gunicorn.socket, служба gunicorn.service не будет активна в связи с отсутствием подключений к совету. Для проверки можно ввести следующую команду:

      • sudo systemctl status gunicorn

      Output

      ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: inactive (dead)

      Чтобы протестировать механизм активации сокета, установим соединение с сокетом через curl с помощью следующей команды:

      • curl --unix-socket /run/gunicorn.sock localhost

      Выводимые данные приложения должны отобразиться в терминале в формате HTML. Это показывает, что Gunicorn запущен и может обслуживать ваше приложение Django. Вы можете убедиться, что служба Gunicorn работает, с помощью следующей команды:

      • sudo systemctl status gunicorn

      Output

      ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: active (running) since Mon 2018-07-09 20:00:40 UTC; 4s ago Main PID: 1157 (gunicorn) Tasks: 4 (limit: 1153) CGroup: /system.slice/gunicorn.service ├─1157 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application ├─1178 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application ├─1180 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application └─1181 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application Jul 09 20:00:40 django1 systemd[1]: Started gunicorn daemon. Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1157] [INFO] Starting gunicorn 19.9.0 Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1157] [INFO] Listening at: unix:/run/gunicorn.sock (1157) Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1157] [INFO] Using worker: sync Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1178] [INFO] Booting worker with pid: 1178 Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1180] [INFO] Booting worker with pid: 1180 Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1181] [INFO] Booting worker with pid: 1181 Jul 09 20:00:41 django1 gunicorn[1157]: - - [09/Jul/2018:20:00:41 +0000] "GET / HTTP/1.1" 200 16348 "-" "curl/7.58.0"

      Если результат вывода curl или systemctl status указывают на наличие проблемы, поищите в журналах более подробные данные:

      • sudo journalctl -u gunicorn

      Проверьте файл /etc/systemd/system/gunicorn.service на наличие проблем. Если вы внесли изменения в файл /etc/systemd/system/gunicorn.service, перезагрузите демона, чтобы заново считать определение службы, и перезапустите процесс Gunicorn с помощью следующей команды:

      • sudo systemctl daemon-reload
      • sudo systemctl restart gunicorn

      Обязательно устраните вышеперечисленные проблемы, прежде чем продолжить.

      Настройка Nginx как прокси для Gunicorn

      Мы настроили Gunicorn, и теперь нам нужно настроить Nginx для передачи трафика в процесс.

      Для начала нужно создать и открыть новый серверный блок в каталоге Nginx sites-available:

      • sudo nano /etc/nginx/sites-available/myproject

      Откройте внутри него новый серверный блок. Вначале мы укажем, что этот блок должен прослушивать обычный порт 80, и что он должен отвечать на доменное имя или IP-адрес нашего сервера:

      /etc/nginx/sites-available/myproject

      server {
          listen 80;
          server_name server_domain_or_IP;
      }
      

      Затем мы укажем Nginx игнорировать любые проблемы при поиске favicon. Также мы укажем, где можно найти статичные ресурсы, собранные нами в каталоге ~/myprojectdir/static. Все эти строки имеют стандартный префикс URI «/static», так что мы можем создать блок location для соответствия этим запросам:

      /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 / {} для соответствия всем другим запросам. В этот блок мы включим стандартный файл proxy_params, входящий в комплект установки Nginx, и тогда трафик будет передаваться напрямую на сокет Gunicorn:

      /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;
          }
      }
      

      Сохраните файл и закройте его после завершения. Теперь мы можем активировать файл, привязав его к каталогу sites-enabled:

      • sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

      Протестируйте конфигурацию Nginx на ошибки синтаксиса:

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

      • sudo systemctl restart nginx

      Нам нужна возможность открыть брандмауэр для обычного трафика через порт 80. Поскольку нам больше не потребуется доступ к серверу разработки, мы можем удалить правило и открыть порт 8000:

      • sudo ufw delete allow 8000
      • sudo ufw allow 'Nginx Full'

      Теперь у вас должна быть возможность перейти к домену или IP-адресу вашего сервера для просмотра вашего приложения.

      Примечание. После настройки Nginx необходимо защитить трафик на сервер с помощью SSL/TLS. Это важно, поскольку в противном случае вся информация, включая пароли, будет отправляться через сеть в простом текстовом формате.

      Если у вас имеется доменное имя, проще всего будет использовать Let’s Encrypt для получения сертификата SSL для защиты вашего трафика. Следуйте указаниям этого руководства, чтобы настроить Let’s Encrypt с Nginx в Ubuntu 18.04. Следуйте процедуре, используя серверный блок Nginx, созданный нами в этом обучающем модуле.

      Если у вас нет доменного имени, вы можете защитить свой сайт для тестирования и обучения с помощью сертификата SSL с собственной подписью. Следуйте процедуре, используя серверный блок Nginx, созданный нами в этом обучающем модуле.

      Диагностика и устранение неисправностей Nginx и Gunicorn

      Если на последнем шаге не будет показано ваше приложение, вам нужно будет провести диагностику и устранение неисправностей установки.

      Nginx показывает страницу по умолчанию, а не приложение Django

      Если Nginx показывает страницу по умолчанию, а не выводит ваше приложение через прокси, это обычно означает, что вам нужно изменить параметр server_name в файле /etc/nginx/sites-available/myproject, чтобы он указывал на IP-адрес или доменное имя вашего сервера.

      Nginx использует server_name, чтобы определять, какой серверный блок использовать для ответа на запросы. Если вы увидите страницу Nginx по умолчанию, это будет означать, что Nginx не может найти явное соответствие запросу в серверном блоке и выводит блок по умолчанию, заданный в /etc/nginx/sites-available/default.

      Параметр server_name в серверном блоке вашего проекта должен быть более конкретным, чем содержащийся в серверном блоке, выбираемом по умолчанию.

      Nginx выводит ошибку 502 Bad Gateway вместо приложения Django

      Ошибка 502 означает, что Nginx не может выступать в качестве прокси для запроса. Ошибка 502 может сигнализировать о разнообразных проблемах конфигурации, поэтому для диагностики и устранения неисправности потребуется больше информации.

      В первую очередь эту информацию следует искать в журналах ошибок Nginx. Обычно это указывает, какие условия вызвали проблемы во время прокси-обработки. Изучите журналы ошибок Nginx с помощью следующей команды:

      • sudo tail -F /var/log/nginx/error.log

      Теперь выполните в браузере еще один запрос, чтобы получить свежее сообщение об ошибке (попробуйте обновить страницу). В журнал будет записано свежее сообщение об ошибке. Если вы изучите его, это поможет идентифицировать проблему.

      Возможно вы увидите сообщение следующего вида:

      connect() to unix:/run/gunicorn.sock failed (2: No such file or directory)

      Это означает, что Nginx не удалось найти файл gunicorn.sock в указанном месте. Вы должны сравнить расположение proxy_pass, определенное в файле etc/nginx/sites-available/myproject, с фактическим расположением файла gunicorn.sock, сгенерированным блоком systemd gunicorn.socket.

      Если вы не можете найти файл gunicorn.sock в каталоге /run, это означает, что файл сокета systemd не смог его создать. Вернитесь к разделу проверки файла сокета Gunicorn и выполните процедуру диагностики и устранения неисправностей Gunicorn.

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

      Это означает, что Nginx не удалось подключиться к сокету Gunicorn из-за проблем с правами доступа. Это может произойти, если процедуру выполнять с привилегиями root, а не с привилегиями sudo. Хотя systemd может создать файл сокета Gunicorn, Nginx не может получить к нему доступ.

      Это может произойти из-за ограничения прав доступа в любом месте между корневым каталогом (/) и файлом gunicorn.sock. Чтобы увидеть права доступа и владельцев файла сокета и всех его родительских каталогов, нужно ввести абсолютный путь файла сокета как параметр команды namei:

      • namei -l /run/gunicorn.sock

      Output

      f: /run/gunicorn.sock drwxr-xr-x root root / drwxr-xr-x root root run srw-rw-rw- root root gunicorn.sock

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

      В приведенном выше примере для файла сокета и каждого из каталогов пути к файлу сокета установлены всеобщие права доступа на чтение и исполнение (запись в столбце разрешений каталогов заканчивается на r-x, а не на ---). Процесс Nginx должен успешно получить доступ к сокету.

      Если для любого из каталогов, ведущих к сокету, отсутствуют глобальные разрешения на чтение и исполнение, Nginx не сможет получить доступ к сокету без включения таких разрешений или без передачи группового владения группе, в которую входит Nginx.

      Django выводит ошибку: «could not connect to server: Connection refused»

      При попытке доступа к частям приложения через браузер Django может вывести сообщение следующего вида:

      OperationalError at /admin/login/
      could not connect to server: Connection refused
          Is the server running on host "localhost" (127.0.0.1) and accepting
          TCP/IP connections on port 5432?
      

      Это означает, что Django не может подключиться к базе данных Postgres. Убедиться в нормальной работе экземпляра Postgres с помощью следующей команды:

      • sudo systemctl status postgresql

      Если он работает некорректно, вы можете запустить его и включить автоматический запуск при загрузке (если эта настройка еще не задана) с помощью следующей команды:

      • sudo systemctl start postgresql
      • sudo systemctl enable postgresql

      Если проблемы не исчезнут, проверьте правильность настроек базы данных, заданных в файле ~/myprojectdir/myproject/settings.py.

      Дополнительная диагностика и устранение неисправностей

      В случае обнаружения дополнительных проблем журналы могут помочь в поиске первопричин. Проверяйте их по очереди и ищите сообщения, указывающие на проблемные места.

      Следующие журналы могут быть полезными:

      • Проверьте журналы процессов Nginx с помощью команды: sudo journalctl -u nginx
      • Проверьте журналы доступа Nginx с помощью команды: sudo less /var/log/nginx/access.log
      • Проверьте журналы ошибок Nginx с помощью команды: sudo less /var/log/nginx/error.log
      • Проверьте журналы приложения Gunicorn с помощью команды: sudo journalctl -u gunicorn
      • Проверьте журналы сокета Gunicorn с помощью команды: sudo journalctl -u gunicorn.socket

      При обновлении конфигурации или приложения вам может понадобиться перезапустить процессы для адаптации к изменениям.

      Если вы обновите свое приложение Django, вы можете перезапустить процесс Gunicorn для адаптации к изменениям с помощью следующей команды:

      • sudo systemctl restart gunicorn

      Если вы измените файл сокета или служебные файлы Gunicorn, перезагрузите демона и перезапустите процесс с помощью следующей команды:

      • sudo systemctl daemon-reload
      • sudo systemctl restart gunicorn.socket gunicorn.service

      Если вы измените конфигурацию серверного блока Nginx, протестируйте конфигурацию и Nginx с помощью следующей команды:

      • sudo nginx -t && sudo systemctl restart nginx

      Эти команды помогают адаптироваться к изменениям в случае изменения конфигурации.

      Заключение

      В этом руководстве мы создали и настроили проект Django в его собственной виртуальной среде. Мы настроили Gunicorn для трансляции запросов клиентов, чтобы Django мог их обрабатывать. Затем мы настроили Nginx в качестве обратного прокси-сервера для обработки клиентских соединений и вывода проектов, соответствующих запросам клиентов.

      Django упрощает создание проектов и приложений, предоставляя множество стандартных элементов и позволяя сосредоточиться на уникальных. Используя описанную в этой статье процедуру, вы сможете легко обслуживать создаваемые приложения на одном сервере.



      Source link

      How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04


      Introdução

      O Django é um framework Web poderoso, que pode ajudar o seu aplicativo Python ou site a decolar. O Django inclui um servidor de desenvolvimento simplificado para testar seu código localmente, mas para qualquer coisa ligeiramente relacionada com produção, é necessário um servidor Web mais seguro e poderoso.

      Neste guia, vamos demonstrar como instalar e configurar alguns componentes no Ubuntu 18.04 para apoiar e servir aplicativos do Django. Vamos configurar um banco de dados PostgreSQL ao invés de usar o banco de dados padrão SQLite. Vamos configurar o servidor do aplicativo Gunicorn para interagir com nossos aplicativos. Então, vamos configurar o Nginx como proxy reverso do Gunicorn, dando-nos acesso aos seus recursos de segurança e desempenho para servir nossos aplicativos.

      Pré-requisitos e objetivos

      Para completar este guia, você deve ter uma nova instância de servidor Ubuntu 18.04 com um firewall básico e um usuário não raiz com privilégios sudo configurados. Você pode aprender como configurar isso examinando nosso guia de configuração inicial do servidor.

      Vamos instalar o Django em um ambiente virtual. Instalar o Django em um ambiente específico do seu projeto permitirá que seus projetos e seus requisitos sejam tratados separadamente.

      Assim que tivermos nosso banco de dados e aplicativo funcionando, vamos instalar e configurar o servidor do aplicativo Gunicorn. Isso servirá como uma interface para nosso aplicativo, traduzindo os pedidos do cliente de HTTP para chamadas Python que nosso aplicativo consegue processar. Então, vamos configurar o Nginx na frente do Gunicorn para aproveitar seus mecanismos de gerenciamento de conexão de alta performance e seus recursos de segurança fáceis de implementar.

      Vamos começar.

      Instalando os pacotes dos repositórios do Ubuntu

      Para começar o processo, vamos baixar e instalar todos os itens que precisamos dos repositórios do Ubuntu. Vamos usar o gerenciador de pacotes Python pip para instalar componentes adicionais um pouco mais tarde.

      Precisamos atualizar o índice de pacotes local apt e, em seguida, baixar e instalar os pacotes. Os pacotes que instalamos dependem da versão do Python que seu projeto usará.

      Se estiver usando o Django com o Python 3, digite:

      • sudo apt update
      • sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl

      O Django 1.11 é a última versão do Django que suportará o Python 2. Se você estiver começando novos projetos, é altamente recomendado que escolha o Python 3. Se ainda for necessário usar o Python 2, digite:

      • sudo apt update
      • sudo apt install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx curl

      Isso instalará o pip, os arquivos de desenvolvimento do Python necessários para criar o Gunicorn mais tarde, o sistema de banco de dados Postgres e as bibliotecas necessárias para interagir com ele, e o servidor Web Nginx.

      Criando o banco de dados e o usuário PostgreSQL

      Vamos ir direto e criar um banco de dados e um usuário do banco de dados para nosso aplicativo Django.

      Por padrão, o Postgres usa um esquema de autenticação chamado de “autenticação por peer” para conexões locais. Basicamente, isso significa que se o nome de usuário do sistema operacional do usuário corresponder a um nome de usuário do Postgres válido, o usuário pode logar-se sem autenticação adicional.

      Durante a instalação do Postgres, um usuário do sistema operacional chamado postgres foi criado para corresponder ao usuário administrativo postgres do PostgreSQL. Precisamos usar este usuário para realizar tarefas administrativas. Podemos usar o sudo e passar o nome de usuário com a opção -u.

      Logue-se em uma sessão interativa do Postgres digitando:

      Você receberá um prompt do PostgreSQL onde podemos configurar nossos requisitos.

      Primeiramente, crie um banco de dados para seu projeto:

      • CREATE DATABASE myproject;

      Nota: Cada declaração do Postgres deve terminar com um ponto e vírgula, para garantir que seu comando termine com um, caso esteja passando por problemas.

      Em seguida, crie um usuário do banco de dados para nosso projeto. Certifique-se de selecionar uma senha segura:

      • CREATE USER myprojectuser WITH PASSWORD 'password';

      Depois disso, vamos modificar alguns dos parâmetros de conexão para o usuário que acabamos de criar. Isso irá acelerar as operações do banco de dados para que os valores corretos não tenham que ser consultados e definidos cada vez que uma conexão for estabelecida.

      Estamos definindo a codificação padrão para UTF-8, que é a que o Django espera. Também estamos definindo o esquema padrão de isolamento de transação para “ler confirmados”, que bloqueia a leitura de transações não confirmadas. Por fim, vamos definir o fuso horário. Por padrão, nossos projetos Django serão configurados para usar o UTC. Essas são todas recomendações do projeto Django em si:

      • 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';

      Agora, podemos dar ao nosso novo usuário acesso para administrar nosso novo banco de dados:

      • GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

      Quando tiver terminado, saia do prompt do PostgreSQL digitando:

      O Postgres agora está configurado para que o Django possa se conectar ao seu banco de dados e gerenciar suas informações.

      Criando um Ambiente Virtual Python para seu Projeto

      Agora que temos nosso banco de dados, podemos começar a preparar o resto dos nossos requisitos do projeto. Vamos instalar nossos requisitos do Python em um ambiente virtual para fácil gerenciamento.

      Para isso, precisamos primeiro acessar o comando virtualenv. Podemos instalar isso com o pip.

      Se estiver usando o Python 3, atualize o pip e instale o pacote digitando:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      Se estiver usando o Python 2, atualize o pip e instale o pacote digitando:

      • sudo -H pip install --upgrade pip
      • sudo -H pip install virtualenv

      Com o virtualenv instalado, podemos começar a formar nosso projeto. Crie um diretório onde possamos manter nossos arquivos do projeto e vá até ele:

      • mkdir ~/myprojectdir
      • cd ~/myprojectdir

      Dentro do diretório do projeto, crie um ambiente virtual do Python digitando:

      Isso criará um diretório chamado myprojectenv dentro do seu diretório myprojectdir. Lá dentro, ele instalará uma versão local do Python e uma versão local do pip. Podemos usar isso para instalar e configurar um ambiente Python isolado para nosso projeto.

      Antes de instalarmos os requisitos Python do nosso projeto, precisamos ativar o ambiente virtual. Você pode fazer isso digitando:

      • source myprojectenv/bin/activate

      Seu prompt deverá mudar para indicar que você agora está operando em um ambiente virtual Python. Eles se parecerão com isso: (myprojectenv)user@host:~/myprojectdir$.

      Com seu ambiente virtual ativo, instale o Django, Gunicorn, e o adaptador do PostgreSQL psycopg2 com a instância local do pip:

      Nota: Quando o ambiente virtual for ativado (quando seu prompt tiver (myprojectenv) antecedendo ele) use o pip ao invés do pip3, mesmo se estiver usando o Python 3. A cópia da ferramenta do ambiente virtual é sempre chamada de pip, independente da versão Python.

      • pip install django gunicorn psycopg2-binary

      Agora, você deve ter todos os softwares necessários para iniciar um projeto Django.

      Criando e Configurando um Projeto Django Novo

      Com nossos componentes Python instalados, podemos criar os arquivos do projeto Django em si.

      Criando o Projeto Django

      Como já temos um diretório de projeto, vamos dizer ao Django para instalar os arquivos aqui. Ele criará um diretório de segundo nível com o código real, o que é normal, e colocará um script de gerenciamento neste diretório. A chave para isso é que estamos definindo o diretório explicitamente ao invés de permitir que o Django tome decisões sobre nosso diretório atual:

      • django-admin.py startproject myproject ~/myprojectdir

      Neste ponto, seu diretório de projeto (~/myprojectdir no nosso caso) deve ter o seguinte conteúdo:

      • ~/myprojectdir/manage.py: um script de gerenciamento de projeto Django.
      • ~/myprojectdir/myproject/: o pacote do projeto Django. Isso deve conter os arquivos __init__.py, settings.py, urls.py e wsgi.py.
      • ~/myprojectdir/myprojectenv/: o diretório do ambiente virtual que criamos anteriormente.

      Ajustando as configurações do Projeto

      A primeira coisa que devemos fazer com nossos arquivos de projeto recém-criados é ajustar as configurações. Abra as configurações no seu editor de texto:

      • nano ~/myprojectdir/myproject/settings.py

      Comece locando a diretriz ALLOWED_HOSTS. Isso define uma lista dos endereços ou nomes de domínio do servidor que podem ser usados para se conectar à instância Django. Qualquer pedido recebido com um cabeçalho Host que não está nesta lista irá criar uma exceção. O Django exige que você defina isso para prevenir uma certa classe de vulnerabilidade de segurança.

      Dentro dos colchetes, liste os endereços IP ou nomes de domínio associados ao seu servidor do Django. Cada item deve ser listado entre aspas, com entradas separadas divididas por uma vírgula. Se você quiser pedidos para um domínio inteiro e quaisquer subdomínios, anteceda um período ao início da entrada. No trecho abaixo, há alguns exemplos comentados usados como demonstração:

      Nota: Certifique-se de incluir o localhost como uma das opções, uma vez que vamos estar passando conexões por um proxy através de uma instância local do Nginx.

      ~/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']
      

      Em seguida, encontre a seção que configura o acesso ao banco de dados. Ela começará com DATABASES. A configuração no arquivo é para um banco de dados SQLite. Já criamos um banco de dados PostgreSQL para nosso projeto, então precisamos ajustar as configurações.

      Altere as configurações com as informações do seu banco de dados PostgreSQL. Diremos ao Django para usar o adaptador psycopg2 que instalamos com o pip. Precisamos fornecer o nome do banco de dados, o nome de usuário do banco de dados, a senha do usuário do banco de dados, e então especificar que o banco de dados está localizado no computador local. Você pode deixar a configuração PORT como uma string vazia:

      ~/myprojectdir/myproject/settings.py

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

      Em seguida, vá até o final do arquivo e adicione uma configuração indicando onde os arquivos estáticos devem ser colocados. Isso é necessário para que o Nginx possa lidar com pedidos para esses itens. A seguinte linha diz ao Django para colocá-los em um diretório chamado static no diretório base do projeto:

      ~/myprojectdir/myproject/settings.py

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

      Salve e feche o arquivo quando você terminar.

      Completando a Configuração Inicial do Projeto

      Agora, podemos migrar o esquema inicial do banco de dados para nosso banco de dados PostgreSQL usando o script de gerenciamento:

      • ~/myprojectdir/manage.py makemigrations
      • ~/myprojectdir/manage.py migrate

      Crie um usuário administrativo para o projeto digitando:

      • ~/myprojectdir/manage.py createsuperuser

      Você terá que selecionar um nome de usuário, fornecer um endereço e-mail, e escolher uma senha e confirmá-la.

      Podemos coletar todos o conteúdo estático no local do diretório que configuramos digitando:

      • ~/myprojectdir/manage.py collectstatic

      Você terá que confirmar a operação. Os arquivos estáticos serão então colocados em um diretório chamado static dentro do seu diretório.

      Se seguiu o guia de configuração inicial do servidor, você deve ter um firewall UFW protegendo seu servidor. Para testar o servidor de desenvolvimento, vamos ter que permitir o acesso à porta que iremos usar.

      Crie uma exceção para a porta 8000 digitando:

      Finalmente, você pode testar nosso projeto iniciando o servidor de desenvolvimento Django com este comando:

      • ~/myprojectdir/manage.py runserver 0.0.0.0:8000

      No seu navegador Web, visite o nome de domínio ou endereço IP do seu servidor seguido de :8000:

      http://server_domain_or_IP:8000
      

      Você deve ver a página inicial padrão do Django:

      Django index page

      Se adicionar /admin no final do URL na barra de endereço, você será solicitado a colocar o nome de usuário administrativo e a senha que criou com o comando createsuperuser:

      Django admin login

      Após a autenticação, você pode acessar a interface de admin do Django padrão:

      Django admin interface

      Quando você terminar de explorar, clique em CTRL-C na janela do terminal para fechar o servidor de desenvolvimento.

      Testando a capacidade do Gunicorn para servir o projeto

      A última coisa que queremos fazer antes de deixar nosso ambiente virtual é testar o Gunicorn para garantir que ele possa servir o aplicativo. Podemos fazer isso entrando no nosso diretório de projeto e usando o gunicorn para carregar o módulo WSGI do projeto:

      • cd ~/myprojectdir
      • gunicorn --bind 0.0.0.0:8000 myproject.wsgi

      Isso irá iniciar o Gunicorn na mesma interface em que o servidor de desenvolvimento do Django estava sendo executado. Você pode voltar e testar o aplicativo novamente.

      Nota: A interface admin não terá qualquer um dos estilos aplicados, uma vez que o Gunicorn não sabe como encontrar o conteúdo CSS estático responsável por isso.

      Passamos um módulo ao Gunicorn especificando o caminho de diretório relativo para o arquivo wsgi.py do Django, que é o ponto de entrada para nosso aplicativo, usando a sintaxe do módulo do Python. Dentro deste arquivo, é definida uma função chamada de application, que é usada para se comunicar com o aplicativo. Para aprender mais sobre a especificação WSGI, clique aqui.

      Quando terminar os testes, clique em CTRL-C na janela do terminal para interromper o Gunicorn.

      Agora, acabamos de configurar nosso aplicativo Django. Podemos sair do nosso ambiente virtual digitando:

      O indicador do ambiente virtual no seu prompt será removido.

      Criando arquivos de socket e de serviço systemd para o Gunicorn

      Nós testamos que o Gunicorn pode interagir com nosso aplicativo Django, mas devemos implementar uma maneira mais robusta de começar e parar o servidor do aplicativo. Para isso, vamos fazer arquivos de serviço e de socket do systemd.

      O socket Gunicorn será criado no boot e escutará as conexões. Quando ocorrer uma conexão, o systemd irá iniciar o processo Gunicorn automaticamente para lidar com a conexão.

      Comece criando e abrindo um arquivo de socket do systemd para o Gunicorn com privilégios sudo:

      • sudo nano /etc/systemd/system/gunicorn.socket

      Dentro, vamos criar uma seção [Unit] para descrever o socket, uma seção [Socket] para definir a localização do socket e uma seção [Install] para garantir que o socket seja criado no momento certo:

      /etc/systemd/system/gunicorn.socket

      [Unit]
      Description=gunicorn socket
      
      [Socket]
      ListenStream=/run/gunicorn.sock
      
      [Install]
      WantedBy=sockets.target
      

      Salve e feche o arquivo quando você terminar.

      Em seguida, crie e abra um arquivo de serviço do systemd para o Gunicorn com privilégios sudo no seu editor de texto. O nome do arquivo de serviço deve corresponder ao nome do arquivo do socket com exceção da extensão:

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

      Comece com a seção [Unit], que é usada para especificar os metadados e dependências. Vamos colocar uma descrição do nosso serviço aqui e dizer ao sistema init para iniciar isso somente após o objetivo da rede ter sido alcançado. Uma vez que nosso serviço se baseia no socket do arquivo do socket, precisamos incluir uma diretriz Requires para indicar essa relação:

      /etc/systemd/system/gunicorn.service

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

      Em seguida, vamos abrir a seção [Service]. Nós especificaremos o usuário e o grupo em que queremos que o processo seja executado. Vamos dar à nossa conta de usuário regular a posse do processo uma vez que ela possui todos os arquivos relevantes. Vamos atribuir a posse do grupo ao grupo www-data para que o Nginx possa se comunicar facilmente com o Gunicorn.

      Então, vamos mapear o diretório em funcionamento e especificar o comando a ser usado para iniciar o serviço. Neste caso, precisaremos especificar o caminho completo para o executável do Gunicorn, que está instalado dentro do nosso ambiente virtual. Vamos ligar o processo ao socket Unix que criamos dentro do diretório /run para que o processo possa se comunicar com o Nginx. Nós registramos todos os dados na saída padrão para que o processo journald possa recolher os registros do Gunicorn. Também podemos especificar quaisquer ajustes opcionais no Gunicorn aqui. Por exemplo, especificamos 3 processos de trabalho neste caso:

      /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 - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 
                myproject.wsgi:application
      

      Finalmente, adicionaremos uma seção [Install]. Isso dirá ao systemd o que ligar a este serviço se nós habilitarmos que ele seja iniciado no boot. Queremos que este serviço comece quando o sistema regular de vários usuários estiver funcionando:

      /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 - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 
                myproject.wsgi:application
      
      [Install]
      WantedBy=multi-user.target
      

      Com isso, nosso arquivo de serviço systemd está completo. Salve e feche-o agora.

      Agora, podemos iniciar e habilitar o socket do Gunicorn. Isso criará o arquivo do socket em /run/gunicorn.sock agora e no boot. Quando uma conexão for feita no socket, o systemd irá iniciar o gunicorn.service automaticamente para lidar com ela:

      • sudo systemctl start gunicorn.socket
      • sudo systemctl enable gunicorn.socket

      Podemos confirmar que a operação foi bem sucedida verificando o arquivo do socket.

      Verificando o arquivo de socket do Gunicorn

      Verifique o status do processo para descobrir se ele foi capaz de iniciar:

      • sudo systemctl status gunicorn.socket

      Em seguida, verifique a existência do arquivo gunicorn.sock dentro do diretório /run:

      Output

      /run/gunicorn.sock: socket

      Se o comando systemctl status indicou que um erro ocorreu ou se você não encontrou o arquivo gunicorn.sock no diretório, é uma indicação de que o socket do Gunicorn não foi criado corretamente. Verifique os registros do socket do Gunicorn digitando:

      • sudo journalctl -u gunicorn.socket

      Veja novamente o seu arquivo /etc/systemd/system/gunicorn.socket para corrigir qualquer problema antes de continuar.

      Testando a ativação do socket

      Se tiver iniciado apenas a unidade gunicorn.socket, o gunicorn.service ainda não estará ativo, já que o socket ainda não recebeu nenhuma conexão. Você pode verificar isso digitando:

      • sudo systemctl status gunicorn

      Output

      ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: inactive (dead)

      Para testar o mecanismo de ativação do socket, podemos enviar uma conexão para o socket através do curl digitando:

      • curl --unix-socket /run/gunicorn.sock localhost

      Você deve ver a saída HTML do seu aplicativo no terminal. Isso indica que o Gunicorn foi iniciado e conseguiu servir seu aplicativo Django. Você pode verificar se o serviço Gunicorn está funcionando digitando:

      • sudo systemctl status gunicorn

      Output

      ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: active (running) since Mon 2018-07-09 20:00:40 UTC; 4s ago Main PID: 1157 (gunicorn) Tasks: 4 (limit: 1153) CGroup: /system.slice/gunicorn.service ├─1157 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application ├─1178 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application ├─1180 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application └─1181 /home/sammy/myprojectdir/myprojectenv/bin/python3 /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application Jul 09 20:00:40 django1 systemd[1]: Started gunicorn daemon. Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1157] [INFO] Starting gunicorn 19.9.0 Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1157] [INFO] Listening at: unix:/run/gunicorn.sock (1157) Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1157] [INFO] Using worker: sync Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1178] [INFO] Booting worker with pid: 1178 Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1180] [INFO] Booting worker with pid: 1180 Jul 09 20:00:40 django1 gunicorn[1157]: [2018-07-09 20:00:40 +0000] [1181] [INFO] Booting worker with pid: 1181 Jul 09 20:00:41 django1 gunicorn[1157]: - - [09/Jul/2018:20:00:41 +0000] "GET / HTTP/1.1" 200 16348 "-" "curl/7.58.0"

      Se o resultado do curl ou o resultado do systemctl status indicar que um problema ocorreu, verifique os registros para mais detalhes:

      • sudo journalctl -u gunicorn

      Verifique seu arquivo /etc/systemd/gunicorn.service quanto a problemas. Se fizer alterações no arquivo /etc/systemd/system/gunicorn.service, recarregue o daemon para reler a definição do serviço e reinicie o processo do Gunicorn digitando:

      • sudo systemctl daemon-reload
      • sudo systemctl restart gunicorn

      Certifique-se de que você tenha resolvido os problemas acima antes de continuar.

      Configurar o Nginx para passagem de proxy para o Gunicorn

      Agora que o Gunicorn está configurado, precisamos configurar o Nginx para passar o tráfego para o processo.

      Inicie criando e abrindo um novo bloco de servidor no diretório sites-available do Nginx:

      • sudo nano /etc/nginx/sites-available/myproject

      Lá dentro, abra um novo bloco de servidor. Vamos começar especificando que este bloco deve escutar a porta normal 80 e que ele deve responder ao nome de domínio ou endereço IP do nosso servidor:

      /etc/nginx/sites-available/myproject

      server {
          listen 80;
          server_name server_domain_or_IP;
      }
      

      Em seguida, vamos dizer ao Nginx para ignorar todos os problemas ao encontrar um favicon. Também vamos dizer a ele onde encontrar os ativos estáticos que coletamos no nosso diretório ~/myprojectdir/static Todos esses arquivos têm um prefixo URI padrão “/static”, então podemos criar um bloco de localização para corresponder a esses pedidos:

      /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;
          }
      }
      

      Por fim, vamos criar um bloco location / {} para corresponder a todos os outros pedidos. Dentro deste local, vamos incluir o arquivo proxy_params padrão incluído na instalação do Nginx e então vamos passar o tráfego diretamente para o socket do Gunicorn:

      /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;
          }
      }
      

      Salve e feche o arquivo quando você terminar. Agora, podemos habilitar o arquivo ligando-o ao diretório sites-enabled:

      • sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

      Teste sua configuração do Nginx para erros de sintaxe digitando:

      Se nenhum erro for reportado, vá em frente e reinicie o Nginx digitando:

      • sudo systemctl restart nginx

      Por fim, precisamos abrir nosso firewall para o tráfego normal na porta 80. Como já não precisamos mais acessar o servidor de desenvolvimento, podemos remover também a regra para abrir a porta 8000:

      • sudo ufw delete allow 8000
      • sudo ufw allow 'Nginx Full'

      Agora, você deve conseguir ir ao domínio ou endereço IP do seu servidor para ver seu aplicativo.

      Nota: Depois de configurar o Nginx, o próximo passo deve ser proteger o tráfego para o servidor usando SSL/TLS. Isso é importante, pois sem ele, todas as informações, incluindo senhas são enviadas para a rede em texto simples.

      Se você tiver um nome de domínio, a maneira mais fácil de obter um certificado SSL para proteger seu tráfego é usando o Let’s Encrypt. Siga este guia para configurar o Let’s Encrypt com o Nginx no Ubuntu 18.04. Siga o procedimento usando o bloco de servidor do Nginx que criamos neste guia.

      Se você não tiver um nome de domínio, ainda é possível proteger seu site como teste e aprendizado com um certificado SSL autoassinado. Novamente, siga o procedimento usando o bloco de servidor do Nginx que criamos neste tutorial.

      Solucionando problemas do Nginx e do Gunicorn

      Se este último passo não mostrar o seu aplicativo, será necessário resolver o problema da sua instalação.

      Nginx está mostrando a página padrão ao invés do aplicativo Django

      Se o Nginx mostra a página padrão em vez de transferir via proxy para seu aplicativo, isso geralmente significa que você precisa ajustar o server_name dentro do arquivo /etc/nginx/sites-available/myproject para apontar ao endereço IP ou nome de domínio do seu servidor.

      O Nginx usa o server_name para determinar qual bloco de servidor usar para responder aos pedidos. Se você estiver vendo a página padrão do Nginx, é um sinal de que o Nginx não conseguiu corresponder ao pedido a um bloco de servidor explicitamente, então ele está recorrendo ao bloco padrão definido em /etc/nginx/sites-available/default.

      O server_name no bloco de servidor do seu projeto deve ser mais específico do que aquele no bloco de servidor padrão para ser selecionado.

      Nginx está exibindo um erro 502 Bad Gateway ao invés do aplicativo Django

      Um erro 502 indica que o Nginx é incapaz de atuar como proxy para o pedido com sucesso. Uma ampla gama de problemas de configuração se expressam com um erro 502, então é necessário mais informações para resolver o problema corretamente.

      O primeiro lugar para procurar mais informações é nos registros de erro do Nginx. Geralmente, isso irá dizer-lhe quais condições causaram problemas durante o evento de proxy. Vá até os registros de erro do Nginx, digitando:

      • sudo tail -F /var/log/nginx/error.log

      Agora, faça outro pedido no seu navegador para gerar um novo erro (tente atualizar a página). Você deve ver uma nova mensagem de erro escrita no registro. Se olhar para a mensagem, ela deve ajudar você a estreitar o problema.

      Pode ser que você veja algumas dessas mensagens:

      connect() to unix:/run/gunicorn.sock failed (2: No such file or directory)

      Isso indica que o Nginx foi incapaz de encontrar o arquivo gunicorn.sock no local indicado. Você deve comparar a localização do proxy_pass definida dentro do arquivo /etc/nginx/sites-available/myproject com a localização real do arquivo gunicorn.sock gerado pela unidade systemd gunicorn.socket.

      Se você não puder encontrar um arquivo gunicorn.sock dentro do diretório /run, isso signica geralmente que o arquivo de socket do systemd foi incapaz de criá-lo. Volte para a seção sobre checar o arquivo de socket do Gunicorn para seguir as etapas de solução de problemas para o Gunicorn.

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

      Isso indica que o Nginx foi incapaz de se conectar ao socket do Gunicorn devido a problemas de permissão. Isso pode acontecer quando o procedimento é seguido usando o usuário raiz ao invés de um usuário sudo. Embora o systemd seja capaz de criar o arquivo de socket do Gunicorn, o Nginx é incapaz de acessá-lo.

      Isso pode acontecer se houver permissões limitadas em qualquer ponto entre o diretório raiz (/) e o arquivo gunicorn.sock. Podemos ver as permissões e os valores de posse do arquivo de socket e cada um dos seus diretórios pais passando o caminho absoluto para nosso arquivo de socket pelo comando namei:

      • namei -l /run/gunicorn.sock

      Output

      f: /run/gunicorn.sock drwxr-xr-x root root / drwxr-xr-x root root run srw-rw-rw- root root gunicorn.sock

      O resultado mostra as permissões de cada um dos componentes do diretório. Ao olhar para as permissões (primeira coluna), proprietário (segunda coluna) e proprietário do grupo (terceiro coluna), podemos descobrir qual tipo de acesso é permitido ao arquivo de socket.

      No exemplo acima, o arquivo de socket e cada um dos diretórios que levam ao arquivo de socket têm permissões de leitura e execução global (a coluna de permissões para os diretórios termina com r-x ao invés de ---). O processo Nginx deve ser capaz de acessar o socket com sucesso.

      Se qualquer um dos diretórios que levam ao socket não tiverem permissão de leitura e execução global, o Nginx não poderá acessar o socket sem permitir permissões de leitura e execução globais ou garantir que o proprietário do grupo seja dado a um grupo do qual o Nginx faça parte.

      Django está exibindo: “could not connect to server: Connection refused”

      Uma mensagem que você pode ver do Django ao tentar acessar partes do aplicativo no navegador Web é:

      OperationalError at /admin/login/
      could not connect to server: Connection refused
          Is the server running on host "localhost" (127.0.0.1) and accepting
          TCP/IP connections on port 5432?
      

      Isso indica que o Django é incapaz de se conectar ao banco de dados do Postgres. Certifique-se de que a instância do Postgres está sendo executada digitando:

      • sudo systemctl status postgresql

      Se não estiver, você pode iniciá-la e habilitá-la para iniciar automaticamente no boot (se ela ainda não estiver configurada para fazer isso) digitando:

      • sudo systemctl start postgresql
      • sudo systemctl enable postgresql

      Se ainda estiver tendo problemas, certifique-se de que as configurações do banco de dados definidas no arquivo ~/myprojectdir/myproject/settings.py estão corretas.

      Soluções de problemas adicionais

      Para soluções de problemas adicionais, os registros podem ajudar a reduzir os problemas de raiz. Verifique cada um deles individualmente e procure mensagens que indiquem áreas de problemas.

      Os registros a seguir podem ser úteis:

      • Verifique os registros de processo do Nginx digitando: sudo journalctl -u nginx
      • Verifique os registros de acesso do Nginx digitando: sudo less /var/log/nginx/access.log
      • Verifique os registros de erro do Nginx digitando: sudo less /var/log/nginx/error.log
      • Verifique os registros do aplicativo Gunicorn digitando: sudo journalctl -u gunicorn
      • Verifique os registros do socket do Gunicorn digitando: sudo journalctl -u gunicorn.socket

      Conforme atualiza sua configuração ou aplicativo, provavelmente precisará reiniciar os processos para ajustá-los às suas alterações.

      Se atualizar seu aplicativo Django, você pode reiniciar o processo Gunicorn para aplicar as alterações, digitando:

      • sudo systemctl restart gunicorn

      Se alterar o socket ou arquivos de serviço do Gunicorn, recarregue o daemon e reinicie o processo, digitando:

      • sudo systemctl daemon-reload
      • sudo systemctl restart gunicorn.socket gunicorn.service

      Se alterar a configuração do bloco de servidor do Nginx, teste a configuração e então o Nginx digitando:

      • sudo nginx -t && sudo systemctl restart nginx

      Estes comandos são úteis para aplicar as alterações conforme você ajusta sua configuração.

      Conclusão

      Neste guia, configuramos um projeto Django em seu próprio ambiente virtual. Configuramos o Gunicorn para traduzir pedidos de clientes para que o Django possa lidar com eles. Depois disso, configuramos o Nginx para agir como um proxy reverso para lidar com conexões de clientes e servir o projeto correto, dependendo da solicitação do cliente.

      O Django torna a criação de projetos e aplicativos simples, fornecendo muitas peças comuns, permitindo que você se concentre nos elementos únicos. Ao utilizar a cadeia de ferramentas geral descrita neste artigo, você pode servir facilmente os aplicativos que criar a partir de um único servidor.



      Source link