One place for hosting & domains

      How To Set Up Django with Postgres, Nginx, and Gunicorn on Debian 10


      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 Debian 10 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.


      In order to complete this guide, you should have a fresh Debian 10 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.

      Step 1 — Installing the Packages from the Debian Repositories

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

      We first need to update the local apt package index, and then download and install the packages.

      In this guide, we’ll use Django with Python 3. To install the necessary libraries, log in to your server and type:

      • sudo apt update
      • sudo apt install python3-pip python3-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.

      Step 2 — 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.

      Step 3 — 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.

      Upgrade pip and install the package by typing:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 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.

      Step 4 — 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:

      • startproject myproject ~/myprojectdir

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

      • ~/myprojectdir/ A Django project management script.
      • ~/myprojectdir/myproject/: The Django project package. This should contain the,,, and 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/

      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.


      . . .
      # The simplest case: just add the domain name(s) and IP addresses of your Django server
      # ALLOWED_HOSTS = [ '', '']
      # To respond to '' and any subdomains, start the domain with a dot
      # ALLOWED_HOSTS = ['', '']
      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:


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


      . . .
      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/ makemigrations
      • ~/myprojectdir/ migrate

      Create an administrative user for the project by typing:

      • ~/myprojectdir/ 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/ 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/ runserver

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


      You should see 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 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 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.

      Step 5 — 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:


      Description=gunicorn socket

      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:


      Description=gunicorn daemon

      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:


      Description=gunicorn daemon
                --access-logfile - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 

      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:


      Description=gunicorn daemon
                --access-logfile - 
                --workers 3 
                --bind unix:/run/gunicorn.sock 

      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.

      Step 6 — 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

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


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

      Step 7 — 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


      ● 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 see 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


      ● 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"

      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.

      Step 8 — 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:


      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:


      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:


      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 Debian 10. Follow the procedure using the Nginx server block we created in this guide.

      If you do not have a domain name, you can still secure your site for testing and learning with a self-signed SSL certificate. Again, follow the process using the Nginx server block we created in this tutorial.

      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 are seeing 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 see a fresh error message written to the log. If you look at the message, it should help you narrow down the problem.

      You might see some of 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 see 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


      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 see 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" ( 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/ 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.


      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.

      You can further optimize this setup by offloading static assets like Javascript and CSS to a CDN or object storage service. To learn how to do this with DigitalOcean Spaces CDN, consult How to Set Up a Scalable Django App with DigitalOcean Managed Databases and Spaces. This tutorial will also show you how to configure SSL/TLS/HTTPS with Nginx, Let’s Encrypt, and Django.

      Source link

      How To Deploy a Go Web Application Using Nginx on Ubuntu 18.04

      The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.


      Go is a general-purpose programming language that is gradually becoming one of the most popular web back-end programming languages. By focusing on simplicity, the designers of Go created a language that is both easy to learn and faster than many other languages for web applications, leveraging efficient features like its ability to handle multiple requests at a time due to its concurrency. Because of this, deploying a web application in Go will be useful to many back-end developers.

      Nginx is one of the most popular web servers in the world due to its lightweight resource usage and its reliability under load. Many of the largest and most highly trafficked sites on the internet depend on Nginx to serve their content. In deployment, Nginx is often used as a load balancer or a reverse proxy to increase security and make the application more robust. In conjunction with a Go web back-end, Nginx can serve up a powerful and fast web application.

      In this tutorial, you will build a Hello World web application in Go and deploy it on an Ubuntu 18.04 server using Nginx as a reverse proxy.


      To follow this tutorial, you will need the following:

      Additionally, in order to achieve a production-grade deployment of your Go web application, it’s important that you keep your server secure by installing a TLS/SSL certificate. This step is strongly encouraged. To secure your Go web application, follow How To Secure Nginx with Let’s Encrypt on Ubuntu 18.04 after Step 3 of this tutorial to obtain the free TLS/SSL certificate.

      Step 1 — Building the Go Web Application

      In this step, you will build a sample Go web application that displays Hello World at your_domain and greets the user at your_domain/greet/. If you would like to learn more about the basics of programming in Go, check out our How To Write Your First Program in Go article.

      First, create a new directory in your GOPATH directory to hold the source file. You can name the folder whatever you like, but this tutorial will use go-web:

      Following the file structure suggested in the prerequisite tutorial How To Install Go and Set Up a Local Programming Environment on Ubuntu 18.04, this will give your directory the path of ~/go/go-web.

      Next, run the following to change directory to your newly created folder in your GOPATH:

      Use nano or your preferred text editor to create a file named main.go, which will contain the source code for your web application:

      To create the functionality of the Hello World application, add the following Go code into the newly created main.go file:


      package main
      import (
      func main() {
          http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintf(w, "Hello World")
          http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
              name := r.URL.Path[len("/greet/"):]
              fmt.Fprintf(w, "Hello %sn", name)
          http.ListenAndServe(":9990", nil)

      Now let's go through what the preceding code snippet will do, starting from the first line.

      First, you wrote the entry point into your application:


      package main

      The package main tells the Go compiler to compile this file as an executable program instead of as a shared library.

      Next, you have the import statements:


      import (

      This snippet imports the necessary modules required for this code to work, which include the standard fmt package and the net/http package for your web server.

      The next snippet creates your first route in the main function, which is the entry point of any Go application:


      func main () {
          http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintf(w, "Hello World")

      A parent route / is created within func main, which will return the text Hello World when requested.

      The second route as shown in the following snippet accepts a URL parameter, in this case a name, to display accompanied by a greeting.


      func main () {
          http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
              name := r.URL.Path[len("/greet/"):]
              fmt.Fprintf(w, "Hello %sn", name)

      This uses Go's URL.Path to store the value right after /greet/ and pass it down as the name from the URL parameter.

      Finally, you instantiate your server:


      func main () {
        http.ListenAndServe(":9990", nil)

      The preceding snippet starts the server and exposes your application via port 9990 using Go's inbuilt http server.

      Once you are finished examining the code in main.go, save the file and quit your text editor.

      Next, build the binary executable of your application by running:

      The preceding command will compile main.go to produce an executable titled main.

      You have created your sample Go web application. Next, you will create a systemd unit file to keep your application running in the background even when you are not accessing your server.

      Step 2 — Creating a Systemd Unit File

      In this step, you will create a systemd unit file to keep your application running in the background even when a user logs out of the server. This will make your application persistent, bringing you one step closer to a production-grade deployment.

      First, create a new file in /lib/systemd/system directory named goweb.service using nano or you preferred text editor:

      • sudo nano /lib/systemd/system/goweb.service

      To set the parameters of the service, add the following snippet into the file.



      The ExecStart=/home/user/go/go-web/main variable specifies that the point of entry for this service is through the main executable located in the /home/user/go/go-web directory, where user is the server non-root sudo account username. Restart=always ensures that systemd will always try to restart the program if it stops. On the next line, RestartSec=5s sets a five-second wait time between restart attempts. specifies in what state your server will enable the service.

      Save and exit the file.

      Now that you've written the service unit file, start your Go web service by running:

      To confirm if the service is running, use the following command:

      • sudo service goweb status

      You'll receive the following output:


      ● goweb.service - goweb Loaded: loaded (/lib/systemd/system/goweb.service; disabled; vendor preset: enabled) Active: active (running) since Wed 2019-07-17 23:28:57 UTC; 6s ago Main PID: 1891 (main) Tasks: 4 (limit: 1152) CGroup: /system.slice/goweb.service └─1891 /home/user/go/go-web/main

      To learn more about working with systemd unit file, take a look at Understanding Systemd Units and Unit Files.

      Now that you have your application up and running, you can set up the Nginx reverse proxy.

      Step 3 — Setting Up a Reverse Proxy with Nginx

      In this step, you will create an Nginx server block and set up an Nginx reverse proxy to expose your application to the internet.

      First, change your working directory to the Nginx sites-available directory:

      • cd /etc/nginx/sites-available

      Create a new file with the name of the domain on which you wish to expose your application. This tutorial will use your_domain:

      Add the following lines into the file to establish the settings for your_domain:


      server {
          server_name your_domain www.your_domain;
          location / {
              proxy_pass http://localhost:9990;

      This Nginx server block uses proxy_pass to serve the Go web application on your server's IP address indicated as localhost to make it run on port 9990. server_name indicates the domain name mapped to your IP address, in this case your_domain and www.your_domain.

      Next, create a symlink of this Nginx configuration in the sites-enabled folder by running the following command:

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

      A symlink is a shortcut of a file in another location. The newly created shortcut will always reference the original file to adjust to updates when edits are made to it. Nginx requires a copy of the configuration in both directories.

      Next, reload your Nginx configurations by running the reload command:

      To make sure that your deployment is working, visit http://your_domain in your browser. You will be greeted with a Hello World text string.

      Note: As mentioned in the Prerequisites section, at this point it is recommended to enable SSL/TLS on your server. This will make sure that all communication between the application and its visitors will be encrypted, which is especially important if the application asks for sensitive information such as a login or password. Follow How To Secure Nginx with Let's Encrypt on Ubuntu 18.04 now to obtain a free SSL certificate for Nginx on Ubuntu 18.04. After obtaining your SSL/TLS certificates, come back and complete this tutorial.

      You have now set up the Nginx reverse proxy to expose your application at your domain name, and secured your Go web application with SSL/TLS. In the next step, you will be testing your application over a secure connection.

      Step 4 — Testing the Application

      In this step, you will test your application over a secure connection to make sure everything is working.

      Open your preferred web browser, visit https://your_domain:

      Hello World Page Display

      You will receive a simple Hello World message. Receiving this message when using https:// in the URL indicates that your application is being served over a secure connection.

      Next, try visiting the second route https://your_domain/greet/your-name, replacing your-name with whichever name you want your app to greet:

      Greeting Page Display

      The application will return a simple greeting along with your-name, which is based on the parameter passed to the URL.

      Once you have received these results, you have successfully deployed your Go web application.


      In this tutorial, you created a simple web application with Go using its standard libraries, set up a reverse proxy using Nginx, and used a SSL certificate on your domain to secure your app. To learn more about Go, check their official documentation. Also, you can look at our series How To Code in Go to learn more about programming in this efficient language.

      Source link

      How To Deploy an ASP.NET Core Application with MySQL Server Using Nginx on Ubuntu 18.04

      The author selected the Open Source Initiative to receive a donation as part of the Write for DOnations program.


      ASP.NET Core is a high-performant, open-source framework for building modern web applications, meant to be a more modular version of Microsoft’s ASP.NET Framework. Released in 2016, it can run on several operating systems such as Linux and macOS. This enables developers to target a particular operating system for development based on design requirements. With ASP.NET Core, a developer can build any kind of web application or service irrespective of the complexity and size. Developers can also make use of Razor pages to create page-focused design working on top of the traditional Model-View-Controller (MVC) pattern.

      ASP.NET Core provides the flexibility to integrate with any front-end frameworks to handle client-side logic or consume a web service. You could, for example, build a RESTful API with ASP.NET Core and easily consume it with JavaScript frameworks such as Angular, React, and Vue.js.

      In this tutorial you’ll set up and deploy a production-ready ASP.NET Core application with a MySQL Server on Ubuntu 18.04 using Nginx. You will deploy a demo ASP.NET Core application similar to the application from Microsoft’s documentation and hosted on GitHub. Once deployed, the demo application will allow you to create a list of movies and store it in the database. You’ll be able to create, read, update, and delete records from the database. You can use this tutorial to deploy your own ASP.NET Core application instead; it’s possible you’ll have to implement extra steps that include generating a new migration file for your database.


      You will need the following for this tutorial:

      Step 1 — Installing .NET Core Runtime

      A .NET Core runtime is required to successfully run a .NET Core application, so you’ll start by installing this to your machine. First, you need to register the Microsoft Key and product repository. After that, you will install the required dependencies.

      First, logged in as your new created user, make sure you’re in your root directory:

      Next, run the following command to register the Microsoft key and product repository:

      • wget -q

      Use dpkg with the -i flag to install the specified file:

      • sudo dpkg -i packages-microsoft-prod.deb

      To facilitate the installation of other packages required for your application, you will install the universe repository with the following command:

      • sudo add-apt-repository universe

      Next install the apt-transport package to allow the use of repositories accessed via the HTTP Secure protocol:

      • sudo apt install apt-transport-https

      Now, run the following command to download the packages list from the repositories and update them to get information on the newest versions of packages and their dependencies:

      Finally, you can install the .NET runtime SDK with:

      • sudo apt install dotnet-sdk-2.2

      You will be prompted with the details of the size of additional files that will be installed. Type Y and hit ENTER to continue.

      Now that you're done installing the .NET Core runtime SDK on the server, you are almost ready to download the demo application from GitHub and set up the deployment configuration. But first, you'll create the database for the application.

      Step 2 — Creating a MySQL User and Database

      In this section, you will create a MySQL server user, create a database for the application, and grant all the necessary privileges for the new user to connect to the database from your application.

      To begin, you need to access the MySQL client using the MySQL root account as shown here:

      You will be prompted to enter the root account password, set up during the prerequisite tutorial.

      Next, create a MySQL database for the application with:

      • CREATE DATABASE MovieAppDb;

      You will see the following output in the console:


      Query OK, 1 row affected (0.03 sec)

      You've now created the database successfully. Next, you will create a new MySQL user, associate them with the newly created database, and grant them all privileges.

      Run the following command to create the MySQL user and password. Remember to change the username and password to something more secure:

      • CREATE USER 'movie-admin'@'localhost' IDENTIFIED BY 'password';

      You will see the following output:


      Query OK, 0 rows affected (0.02 sec)

      To access a database or carry out a specific action on it, a MySQL user needs the appropriate permission. At the moment movie-admin does not have the appropriate permission over the application database.

      You will change that by running the following command to grant access to movie-admin on MovieAppDb:

      • GRANT ALL PRIVILEGES ON MovieAppDb.* TO 'movie-admin'@'localhost';

      You will see the following output:


      Query OK, 0 rows affected (0.01 sec)

      Now, you can reload the grant tables by running the following command to apply the changes that you just made using the flush statement:

      You will see the following output:


      Query OK, 0 rows affected (0.00 sec)

      You are done creating a new user and granting privileges. To test if you are on track, exit the MySQL client:

      Log in again, using the credentials of the MySQL user you just created and enter the appropriate password when prompted:

      Check to be sure that the user movie-admin can access the created database, check with:

      You will see the MovieAppDb table listed in the output:


      +--------------------+ | Database | +--------------------+ | MovieAppDb | | information_schema | +--------------------+ 2 rows in set (0.01 sec)

      Now, exit the MySQL client:

      You've created a database, made a new MySQL user for the demo application, and granted the newly created user the right privileges to access the database. In the next section, you will start setting up the demo application.

      Step 3 — Setting Up the Demo App and Database Credentials

      As stated earlier, you'll deploy an existing ASP.NET Core application. This application was built to create a movie list and it uses the Model-View-Controller design pattern to ensure a proper structure and separation of concerns. To create or add a new movie to the list, the user will populate the form fields with the appropriate details and click on the Create button to post the details to the controller. The controller at this point will receive a POST HTTP request with the submitted details and persist the data in the database through the model.

      You will use Git to pull the source code of this demo application from GitHub and save it in a new directory. You could also download an alternate application here if you will be deploying a different application.

      To begin, create a new directory named movie-app from the terminal by using the following command:

      • sudo mkdir -p /var/www/movie-app

      This will serve as the root directory for your application. Next, change the folder owner and group in order to allow a non-root user account to work with the project files:

      • sudo chown sammy:sammy /var/www/movie-app

      Replace sammy with your sudo non-root username.

      Now, you can move into the parent directory and clone the application on GitHub:

      • cd /var/www
      • git clone movie-app

      You will see the following output:


      Cloning into 'movie-app'... remote: Enumerating objects: 91, done. remote: Counting objects: 100% (91/91), done. remote: Compressing objects: 100% (73/73), done. remote: Total 91 (delta 13), reused 91 (delta 13), pack-reused 0 Unpacking objects: 100% (91/91), done.

      You have successfully cloned the demo application from GitHub, so the next step will be to create a successful connection to the application database. You will do this by editing the ConnectionStrings property within the appsettings.json file and add the details of the database.

      Change directory into the application:

      Now open the file for editing:

      • sudo nano appsettings.json

      Add your database credentials:


        "Logging": {
          "LogLevel": {
            "Default": "Warning"
        "AllowedHosts": "*",
        "ConnectionStrings": {
          "MovieContext": "Server=localhost;User Id=movie-admin;Password=password;Database=MovieAppDb"

      With this in place, you've successfully created a connection to your database. Now press CTRL+X to save your changes to the file and type Y to confirm. Then hit ENTER to exit the page.

      ASP.NET Core applications use a .NET standard library named Entity Framework (EF) Core to manage interaction with the database. Entity Framework Core is a lightweight, cross-platform version of the popular Entity Framework data access technology. It is an object-relational mapper (ORM) that enables .NET developers to work with a database using any of the database providers, such as MySQL.

      You can now update your database with the tables from the cloned demo application. Run the following command for that purpose:

      • dotnet ef database update

      This will apply an update to the database and create the appropriate schemas.

      Now, to build the project and all its dependencies, run the following command:

      You will see output similar to:


      Microsoft (R) Build Engine version 16.1.76+g14b0a930a7 for .NET Core Copyright (C) Microsoft Corporation. All rights reserved. Restore completed in 95.09 ms for /var/www/movie-app/MvcMovie.csproj. MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.dll MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.Views.dll Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:01.91

      This will build the project and install any third-party dependencies listed in the project.assets.json file but the application won’t be ready for production yet. To get the application ready for deployment, run the following command:

      You will see the following:


      Microsoft (R) Build Engine version 16.1.76+g14b0a930a7 for .NET Core Copyright (C) Microsoft Corporation. All rights reserved. Restore completed in 89.62 ms for /var/www/movie-app/MvcMovie.csproj. MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.dll MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/MvcMovie.Views.dll MvcMovie -> /var/www/movie-app/bin/Debug/netcoreapp2.2/publish/

      This will pack and compile the application, read through its dependencies, publish the resulting set of files into a folder for deployment, and produce a cross-platform .dll file that uses the installed .NET Core runtime to run the application.

      By installing dependencies, creating a connection to the database, updating the database with the necessary tables, and publishing it for production, you've completed the setup for this demo application. In the next step you will configure the web server to make the application accessible and secure at your domain.

      Step 4 — Configuring the Web Server

      By now, having followed the How To Secure Nginx with Let's Encrypt tutorial, you'll have a server block for your domain at /etc/nginx/sites-available/your_domain with the server_name directive already set appropriately. In this step, you will edit this server block to configure Nginx as a reverse proxy for your application. A reverse proxy is a server that sits in front of web servers and forwards every web browser’s request to those web servers. It receives all requests from the network and forwards them to a different web server.

      In the case of an ASP.NET Core application, Kestrel is the preferred web server that is included with it by default. It is great for serving dynamic content from an ASP.NET Core application as it provides better request-processing performance and was designed to make ASP.NET as fast as possible. However, Kestrel isn't considered a full-featured web server because it can't manage security and serve static files, which is why it is advisable to always run it behind a web server.

      To begin, ensure that you are within the root directory of your server:

      Open the server block for editing with:

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

      As detailed in the Step 4 of the How To Secure Nginx with Let's Encrypt tutorial, if you selected option 2, Certbot will automatically configure this server block in order to redirect HTTP traffic to HTTPS with just a few modifications.

      Continue with the configuration by editing the first two blocks in the file to reflect the following:


      server {
          server_name your-domain  www.your-domain;
         location / {
           proxy_pass http://localhost:5000;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection keep-alive;
           proxy_set_header Host $host;
           proxy_cache_bypass $http_upgrade;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Proto $scheme;
      listen [::]:443 ssl ipv6only=on; # managed by Certbot
      listen 443 ssl; # managed by Certbot
      ssl_certificate /etc/letsencrypt/live/your-domain/fullchain.pem; # managed by Certbot
      ssl_certificate_key /etc/letsencrypt/live/your-domain/privkey.pem; # managed by Certbot
      include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
      ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

      The configuration in this server block will instruct Nginx to listen on port 443, which is the standard port for websites that use SSL. Furthermore, Nginx will accept public traffic on port 443 and forward every matching request to the built-in Kestrel server at http://localhost:5000.

      Finally, following the server block you just edited in the file, ensure that the second server block looks like so:


      server {
      if ($host = www.your-domain) {
          return 301 https://$host$request_uri;
      } # managed by Certbot
      if ($host = your-domain) {
          return 301 https://$host$request_uri;
      } # managed by Certbot
          listen 80;
          listen [::]:80;
          server_name your-domain  www.your-domain;
      return 404; # managed by Certbot

      This server block will redirect all requests to https://your-domain and https://www.your-domain to a secure HTTPS access.

      Next, force Nginx to pick up the changes you've made to the server block by running:

      With the Nginx configuration successfully completed, the server is fully set up to forward all HTTPS requests made to https://your-domain on to the ASP.NET Core app running on Kestrel at http://localhost:5000. However, Nginx isn’t set up to manage the Kestrel server process. To handle this and ensure that the Kestrel process keeps running in the background, you will use systemd functionalities.

      Systemd files will allow you to manage a process by providing start, stop, restart, and log functionalities once you create a process of work called a unit.

      Move into the systemd directory:

      Create a new file for editing:

      Add the following content to it:


      Description=Movie app
      ExecStart=/usr/bin/dotnet /var/www/movie-app/bin/Debug/netcoreapp2.2/publish/MvcMovie.dll

      The configuration file specifies the location of the project’s folder with WorkingDirectory and the command to execute at the start of the process in ExecStart. In addition, you've used the RestartSec directive to specify when to restart the systemd service if the .NET runtime service crashes.

      Now save the file and enable the new movie service created with:

      • sudo systemctl enable movie.service

      After that, proceed to start the service and verify that it’s running by starting the service:

      • sudo systemctl start movie.service

      Then check its status:

      • sudo systemctl status movie.service

      You will see the following output:


      movie.service - Movie app Loaded: loaded (/etc/systemd/system/movie.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2019-06-23 04:51:28 UTC; 11s ago Main PID: 6038 (dotnet) Tasks: 16 (limit: 1152) CGroup: /system.slice/movie.service └─6038 /usr/bin/dotnet /var/www/movie-app/bin/Debug/netcoreapp2.2/publish/MvcMovie.dll

      This output gives you an overview of the current status of the movie.service created to keep your app running. It indicates that the service is enabled and currently active.

      Navigate to https://your-domain from your browser to run and test out the application.

      You'll see the home page for the demo application—Movie List Application.

      Movie list application

      With the reverse proxy configured and Kestrel managed through systemd, the web app is fully configured and can be accessed from a browser.


      In this tutorial, you deployed an ASP.NET Core application to an Ubuntu server. To persist and manage data, you installed and used MySQL server and used the Nginx web server as a reverse proxy to serve your application.

      Beyond this tutorial, if you're interested in building an interactive web application using C# instead of Javascript you could try a web UI framework by Microsoft called Blazor. It is an event-driven component-based web UI for implementing logic on the client side of an ASP.NET Core application.

      If you wish to deploy your own application, you'll need to consider other required procedures to deploy your app. The complete source code for this demo application can be found here on GitHub.

      Source link