How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 20.04 | DigitalOcean (2023)

A previous version of this article was written by Justin Ellingwood.

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:

  1. sudo apt update
  2. 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:

  1. sudo apt update
  2. 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:

  1. sudo -u postgres psql

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

First, create a database for your project:

  1. 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:

  1. 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:

  1. ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
  2. ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
  3. ALTER ROLE myprojectuser SET timezone TO 'UTC';

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

  1. GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

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

  1. \q

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:

  1. sudo -H pip3 install --upgrade pip
  2. sudo -H pip3 install virtualenv

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

  1. sudo -H pip install --upgrade pip
  2. 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:

(Video) How to Set Up Django with PostgreSQL, Nginx, and Gunicorn on Ubuntu 18.04

  1. mkdir ~/myprojectdir
  2. cd ~/myprojectdir

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

  1. virtualenv myprojectenv

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:

  1. 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.

  1. 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:

  1. django-admin 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:

  1. 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/'import osSTATIC_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:

  1. ~/myprojectdir/manage.py makemigrations
  2. ~/myprojectdir/manage.py migrate

Create an administrative user for the project by typing:

  1. ~/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:

  1. ~/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:

  1. sudo ufw allow 8000

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

  1. ~/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:

(Video) Django | Server Setup (WSGI, Gunicorn, Nginx)

http://server_domain_or_IP:8000

You should receive the default Django index page:

How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 20.04 | DigitalOcean (1)

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:

How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 20.04 | DigitalOcean (2)

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

How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 20.04 | DigitalOcean (3)

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:

  1. cd ~/myprojectdir
  2. 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:

  1. deactivate

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:

  1. 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:

  1. 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 daemonRequires=gunicorn.socketAfter=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 daemonRequires=gunicorn.socketAfter=network.target[Service]User=sammyGroup=www-dataWorkingDirectory=/home/sammy/myprojectdirExecStart=/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 daemonRequires=gunicorn.socketAfter=network.target[Service]User=sammyGroup=www-dataWorkingDirectory=/home/sammy/myprojectdirExecStart=/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:

(Video) Deploy Django with Nginx , Gunicorn , PostgreSQL on Linux Server

  1. sudo systemctl start gunicorn.socket
  2. 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:

  1. 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:

  1. file /run/gunicorn.sock

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:

  1. 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:

  1. 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:

  1. 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:

  1. 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 agoTriggeredBy: ● 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.4Jun 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: syncJun 26 18:52:21 django-tutorial gunicorn[22927]: [2020-06-26 18:52:21 +0000] [22927] [INFO] Booting worker with pid: 22927Jun 26 18:52:21 django-tutorial gunicorn[22928]: [2020-06-26 18:52:21 +0000] [22928] [INFO] Booting worker with pid: 22928Jun 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:

  1. 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:

  1. sudo systemctl daemon-reload
  2. 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:

  1. 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:

  1. sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

Test your Nginx configuration for syntax errors by typing:

  1. sudo nginx -t

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

  1. 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:

  1. sudo ufw delete allow 8000
  2. 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.

(Video) How To install Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04

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:

  1. 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:

  1. namei -l /run/gunicorn.sock

Output

f: /run/gunicorn.sockdrwxr-xr-x root root /drwxr-xr-x root root runsrw-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:

  1. 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:

  1. sudo systemctl start postgresql
  2. 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:

  1. sudo systemctl restart gunicorn

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

  1. sudo systemctl daemon-reload
  2. sudo systemctl restart gunicorn.socket gunicorn.service

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

(Video) How to install python, postgreSQL, django, gunicorn and nginx on ubuntu

  1. 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.

FAQs

How to deploy Django using Gunicorn and nginx? ›

How to host Django Application using gunicorn & nginx in...
  1. Step 1 - Installing python and nginx. ...
  2. Step 2 - Creating a python virtual environment. ...
  3. Step 3 - Installing Django and gunicorn. ...
  4. Step 4 - Setting up our Django project. ...
  5. Step 5 - Configuring gunicorn. ...
  6. Step 6 - Configuring Nginx as a reverse proxy.

How to set up Django with Postgres nginx and Gunicorn on Debian? ›

  1. Install Dependencies. Log in to the server with a non-root sudo user via SSH. ...
  2. Install PostgresSQL. ...
  3. Setup the Python Environment. ...
  4. Upload or Create the Django Project. ...
  5. Configure Gunicorn. ...
  6. Configure Nginx. ...
  7. (Optional) Add HTTPS with Let's Encrypt.
Nov 23, 2022

How to deploy Django with Gunicorn? ›

Running Django in Gunicorn as a generic WSGI application

This will start one process running one thread listening on 127.0. 0.1:8000 . It requires that your project be on the Python path; the simplest way to ensure that is to run this command from the same directory as your manage.py file.

Do I need nginx in front of Gunicorn? ›

Technically, you don't really need Nginx. BUT it's the Internet: your server will receive plenty of malformed HTTP requests which are made by bots and vulnerability scanner scripts. Now, your Gunicorn process will be busy parsing and dealing with these requests instead of serving genuine clients.

How do Gunicorn and nginx work together? ›

Nginx and Gunicorn work together

Gunicorn translates requests which it gets from Nginx into a format which your web application can handle, and makes sure that your code is executed when needed. They make a great team! Each can do something, which the other can't.

How to set up Django with Postgres? ›

Steps
  1. Step 1 — Install and Configure Python 3. ...
  2. Step 2 — Install PostgreSQL. ...
  3. Step 3 — Configure PostgreSQL. ...
  4. Step 4 — Create a Virtual Environment. ...
  5. Step 5 — Install Django. ...
  6. Step 6 — Generate a Django Project. ...
  7. Step 7 — Start a Django App. ...
  8. Step 8 — Configure the Database Connection.
Aug 12, 2022

Is Gunicorn the same as nginx? ›

Gunicorn implements the Web Server Gateway Interface (WSGI), which is a standard interface between web server software and web applications. Nginx is a web server. It's the public handler, more formally called the reverse proxy, for incoming requests and scales to thousands of simultaneous connections.

Should I use Apache or nginx for Django? ›

Both nginx and Apache are excellent choices for a web server. Most people deploying Django nowadays seem to be using nginx, so, if you aren't interested in learning more about what you should choose, pick up nginx. Apache is also widely used, and it is preferable in some cases.

How to deploy Django application on Ubuntu? ›

High level steps to deploy a Django web app to digitalocean ubuntu 20.04 server
  1. Edit settings file to add new hosts.
  2. Test that gunicorn was installed correctly.
  3. Create gunicorn systemd service file.
  4. Configure Nginx to serve your web app.

Do you need Gunicorn with Django? ›

Gunicorn takes care of everything which happens in-between the web server and your web application. This way, when coding up your a Django application you don't need to find your own solutions for: communicating with multiple web servers. reacting to lots of web requests at once and distributing the load.

What is the best way to deploy Django? ›

Django websites can be deployed on any number of hosting providers. The first choice is deciding whether to use a Platform-as-a-service (PaaS) option or a virtual private server (VPS). A PaaS is an easier albeit more expensive option that can handle many deployment issues with minimal configuration.

What is the best way to deploy a Django app to production? ›

To learn where and how you can deploy a Django app to production.
...
Overview
  1. Make a few changes to your project settings.
  2. Choose an environment for hosting the Django app.
  3. Choose an environment for hosting any static files.
  4. Set up a production-level infrastructure for serving your website.
Feb 23, 2023

How do I make my Django site responsive? ›

Quickstart
  1. Install django-responsive2: pip install django-responsive2.
  2. Add responsive to INSTALLED_APPS: INSTALLED_APPS = ( ... ' responsive', ... )
  3. Add django. core. context_processors. request and responsive. ...
  4. Add the ResponsiveMiddleware to MIDDLEWARE_CLASSES: MIDDLEWARE_CLASSES = ( ... 'responsive. middleware.

How to serve flask applications with gunicorn and nginx on ubuntu 20? ›

  1. Prerequisites.
  2. Step 1 — Installing the Components from the Ubuntu Repositories.
  3. Step 2 — Creating a Python Virtual Environment.
  4. Step 3 — Setting Up a Flask Application.
  5. Step 4 — Configuring Gunicorn.
  6. Step 5 — Configuring Nginx to Proxy Requests.
  7. Step 6 — Securing the Application.
  8. Conclusion.
May 10, 2022

Which is the recommended way to install nginx in ubuntu? ›

  1. Installing Nginx. To install Nginx, use following command: sudo apt update sudo apt install nginx. ...
  2. Creating our own website. Default page is placed in /var/www/html/ location. ...
  3. Setting up virtual host. ...
  4. Activating virtual host and testing results.

How to deploy Django with nginx? ›

  1. Some notes about this tutorial.
  2. Concept.
  3. Before you start setting up uWSGI. virtualenv. ...
  4. Basic uWSGI installation and configuration. Install uWSGI into your virtualenv. ...
  5. Basic nginx. Install nginx. ...
  6. nginx and uWSGI and test.py.
  7. Using Unix sockets instead of ports. ...
  8. Running the Django application with uwsgi and nginx.

Should Gunicorn run as root? ›

Gunicorn should not be run as root because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as nginx or Apache httpd should be used in front of Gunicorn.

How to setup Django with PostgreSQL digital ocean? ›

Deploy Django using Postgres, Nginx in digital ocean ubuntu...
  1. Step 1: Digital Ocean sign in or sign up. ...
  2. Step 2: Create Droplet. ...
  3. Step 3: configure droplet. ...
  4. Step 4: Access the created droplet. ...
  5. Step 5: push the code to the remote server(droplet). ...
  6. Step 6: log in to your droplet. ...
  7. Step 7: Create a database. ...
  8. Step 8: do migrate.
Jan 8, 2022

How many threads should I use Gunicorn? ›

Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. Gunicorn relies on the operating system to provide all of the load balancing when handling requests. Generally we recommend (2 x $num_cores) + 1 as the number of workers to start off with.

How to use PostgreSQL with your Django application on Ubuntu? ›

Installing Django with PostgreSQL on Ubuntu
  1. Install Subversion. sudo apt-get install subversion.
  2. Checkout Django. svn co https://code.djangoproject.com/svn/django/trunk django_trunk.
  3. Tell Python where Django is. ...
  4. Add django-admin.py to your PATH. ...
  5. Install PostgreSQL and Psycopg2. ...
  6. Verify the installation. ...
  7. Where to go from here.

Is PostgreSQL good for Django? ›

Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.

Should I use PostgreSQL or MySQL for Django? ›

Django provides support for a number of data types which will only work with PostgreSQL. There is no fundamental reason why (for example) a contrib. mysql module does not exist, except that PostgreSQL has the richest feature set of the supported databases so its users have the most to gain.”

Which server does Django use? ›

Django's primary deployment platform is WSGI, the Python standard for web servers and applications.

Is there anything better than NGINX? ›

HAProxy, lighttpd, Traefik, Caddy, and Envoy are the most popular alternatives and competitors to NGINX.

What can I use instead of Gunicorn? ›

GunicornCompetitors and Alternatives
  • NGINX. Compare.
  • Microsoft IIS. Compare.
  • Oracle WebLogic. Compare.
  • Apache Tomcat. Compare.
  • Microsoft Application Server (deprecated) Compare.
  • IBM WebSphere Hybrid Edition. Compare. Learn More.
  • Red Hat JBoss EAP. Compare.
  • SAP NetWeaver AS. Compare.

Which database is best for Python Django? ›

Postgresql is the preferred database for Django applications due to its open-source nature; and it's also ideal for complex queries.

Is NGINX still faster than Apache? ›

Performance – NGINX performs faster than Apache in providing static content, but it needs help from another piece of software to process dynamic content requests. On the other hand, Apache can handle dynamic content internally.

Do professionals use Django? ›

Django is a Python-based web framework giving developers the tools they need for rapid, hassle-free development. You can find that several major companies employ Django for their development projects.

How do I deploy an application in Ubuntu? ›

Deploying to an Ubuntu server
  1. #Prerequisites.
  2. #Install required dependencies.
  3. #Add a deployment user.
  4. #Add a directory for your app.
  5. #Create a PostgreSQL database.
  6. #Deploying your app.
  7. #Creating a systemd unit file for your app.
  8. #Install and configure nginx as a frontend webserver.

How do I deploy a python project in Ubuntu? ›

Flask will work as the web service Framework which will be implemented in the Python code.
  1. Step 1 — Installations. ...
  2. Step 2 — Create a Virtual Environment. ...
  3. Step 3 — Installing Flask and Gunicorn. ...
  4. Step 4 — Hosting a demo file. ...
  5. Step 5 — Creating a service. ...
  6. Step 6 — Nginx.

How do I connect to Django database? ›

We use the following steps to establish the connection between Django and MySQL.
  1. Step - 1: Create a virtual environment and setting up the Django project.
  2. Step - 2 Create new Database.
  3. Step - 3: Update the settings.py.
  4. Step - 4 Install mysqlclient package.
  5. Step - 5 Run the migrate command.

What is the difference between ModelForm and form Django? ›

The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.

How do I create two models in Django? ›

Creating models
  1. from django. db import models.
  2. # Create your models here.
  3. from django. db import models.
  4. class Question(models. Model):
  5. question_text = models. CharField(max_length=200)
  6. pub_date = models. DateTimeField('date published')
  7. class Choice(models. Model):
  8. question = models. ForeignKey('Question',
Nov 2, 2018

How do I make two forms on the same page Django? ›

Include Multiple Different Forms on the Same Page
  1. Step 1: Create the Forms. To delete the Blog instance, create a new form, DeleteBlogForm . ...
  2. Step 2: Include the Forms in a View. Now that we have the forms, let's handle them in a view. ...
  3. Step 3: Add the Template. ...
  4. Step 4: Add the URL Pattern. ...
  5. Step 5: Link to the Edit Blog Page.
Feb 3, 2022

Which is better Apache or NGINX? ›

Is Apache Better than NGINX? In terms of performance, NGINX is much better than Apache. NGINX performs 2.5 times faster than Apache — and consumes less memory as well.

Do I need a webserver for Django? ›

Django, being a web framework, needs a web server in order to operate. And since most web servers don't natively speak Python, we need an interface to make that communication happen. Django currently supports two interfaces: WSGI and ASGI.

Should I install Django for every project? ›

It is recommended to install Django inside each virtual environment that you create for your project. Django can be installed easily using pip within each of your active Python virtual environments. This way, you can have a separate Django version and its dependencies that are unique for each project.

Is Django faster than node? ›

The fact that the Django web framework is more dynamic and gives fast speed makes it more cost-effective than Node. js. The fact that Node. js absorbs more functioning time, even though it is easier to learn, makes it less cost-effective than Django.

Which environment is best for Django? ›

The Django developer team itself recommends that you use Python virtual environments!

What is the best frontend for Django? ›

In my opinion, the best way to use Django for web applications is to use it to build a REST API and use front-end frameworks — React. js, Angular. js, Ember. js, Vue.

How do I run Django with Gunicorn? ›

Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 20.04
  1. Introduction. Prerequisites.
  2. Install Required Packages.
  3. Install and Configure PostgreSQL.
  4. Create a Python Virtual Environment.
  5. Install and Configure Django.
  6. Test the Django Development Server.
  7. Test Gunicorn.
  8. Create a Systemd Service File for Gunicorn.

Where should I host my Django app? ›

Therefore, for demanding projects built on Django, servers from Amazon, Microsoft, and Google are often optimal even with high prices.
  1. Amazon Web Services (AWS)
  2. Azure (Microsoft)
  3. Google Cloud Platform.
  4. Hetzner.
  5. DigitalOcean.
  6. Heroku.
Dec 30, 2022

How do I deploy a Django project to my website? ›

You can use Visual Studio Code or your favorite text editor.
  1. Step 1: Creating a Python Virtual Environment for your Project. ...
  2. Step 2: Creating the Django Project. ...
  3. Step 3: Pushing the Site to GitHub. ...
  4. Step 4: Deploying to DigitalOcean with App Platform. ...
  5. Step 5: Deploying Your Static Files.
Sep 29, 2021

How do I activate the virtual environment in Django? ›

Type the following in the command prompt, remember to navigate to where you want to create your project:
  1. py -m venv myworld. Unix/MacOS: python -m venv myworld.
  2. myworld\Scripts\activate.bat. Unix/MacOS: source myworld/bin/activate.
  3. (myworld) C:\Users\Your Name> Unix/MacOS: (myworld) ... $

How to connect frontend and backend in Django? ›

The Full-Stack Django Series: How to Combine Frontend and Backend.
...
Workflow
  1. When user visits the website, web server process the request, render HTML using Django template or Jinja.
  2. The browser download CSS, JS and other assets.
  3. The browser run Javascript to sprinkle the server-rendered HTML.
Aug 3, 2022

How to set up Django with Postgres nginx and Gunicorn on CentOS 7? ›

Deploy Django and Flask Applications in the cloud using Nginx, Gunicorn and Systemd (CentOS 7)
  1. Step 1: Install Packages. CentOS comes with multiple package managers such as yum, rpm and dnf. ...
  2. Step 2: Setup your Django/Flask Application. ...
  3. Step 3: Create a Gunicorn Systemd Service File. ...
  4. Step 4: Configure Nginx.

Can I use nginx with Django? ›

It takes you through the steps required to set up Django so that it works nicely with uWSGI and nginx. It covers all three components, providing a complete stack of web application and server software. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

How to deploy Django project with PostgreSQL? ›

Deploy Django with PostgreSQL
  1. Steps to deploy Django with Qovery.
  2. Django application. Django sample application. Select application port. Use Dockerfile.
  3. PostgreSQL. Deploy a PostgreSQL database. Connect your Django application to PostgreSQL.
  4. Deploy your application.
Dec 22, 2022

How do I serve flask applications with Gunicorn and nginx on Centos 8? ›

Deploy flask with gunicorn and nginx (Step-by-Step)
  1. Introduction – Deploy Flask with Nginx using Gunicorn+Nginx.
  2. Lab Environment.
  3. Step-1: Install pre-requisite packages. ...
  4. Step-2: Create Python Virtual Environment.
  5. Step-3: Install flask and gunicorn packages.
  6. Step-4: Setup Flask Web Application. ...
  7. Step-5: Configure Gunicorn.

How to setup a SSL certificate on nginx for a Django application? ›

  1. 5 Steps to deploy Django application using Nginx, Reverse Proxy and Gunicorn including SSL Certificate. ...
  2. Step 1: Setting Django for deployment. ...
  3. Step 2: Setting Gunicorn with systemd service file. ...
  4. Step 3: Configure Nginx to Proxy Pass to Gunicorn. ...
  5. Step 4: Configure SSL Certificate using CertBot. ...
  6. Step 5: Test your result.
Jul 16, 2020

How to set up Django with Postgres NGINX and Gunicorn on Ubuntu 22? ›

  1. Prerequisites and Goals.
  2. Installing the Packages from the Ubuntu Repositories.
  3. Creating the PostgreSQL Database and User.
  4. Creating a Python Virtual Environment for your Project.
  5. Creating and Configuring a New Django Project.
  6. Creating systemd Socket and Service Files for Gunicorn.
  7. Checking for the Gunicorn Socket File.
Apr 25, 2022

What is NGINX and Gunicorn Django? ›

Gunicorn implements the Web Server Gateway Interface (WSGI), which is a standard interface between web server software and web applications. Nginx is a web server. It's the public handler, more formally called the reverse proxy, for incoming requests and scales to thousands of simultaneous connections.

Should I use Apache or NGINX for Django? ›

Both nginx and Apache are excellent choices for a web server. Most people deploying Django nowadays seem to be using nginx, so, if you aren't interested in learning more about what you should choose, pick up nginx. Apache is also widely used, and it is preferable in some cases.

Videos

1. How To Deploy/Host Django On Nginx and Gunicorn - Ubuntu 22
(Learn Python)
2. How deploy a Django application using Nginx & Gunicorn in Production
(CodeWithHarry)
3. Deploy Django Postgres Nginx Gunicorn
(DevOps)
4. Deploy Django website in Ubuntu server with Nginx Gunicorn PostgreSQL DB and apply SSL | Sleeksoft
(Sleeksoft)
5. Django Tutorial - Deploy Django to the production server with Gunicorn and Nginx #21
(Python Lessons)
6. How to deploy a Django project with DigitalOcean
(JustDjango)
Top Articles
Latest Posts
Article information

Author: Laurine Ryan

Last Updated: 03/06/2023

Views: 5493

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.