Set up Django on Ubuntu 16.04 with PostgreSQL and Gunicorn on ECS

Here, we will install and configure a PostgreSQL database and ** Django ** using ** Gunicorn ** on a ** Alibaba Cloud ECS instance ** using Ubuntu 16.04.

Prerequisites

1, Alibaba Cloud Ubuntu 16.04 instance. 2. A fixed IP address is set. 3. The root password is set for the instance.

Launch an ECS instance

First, log in to Alibaba Cloud ECS Console. Create a new ECS instance and Ubuntu as an operating system with at least 2GB of RAM Select 16.04. Connect to the ECS instance (https://www.alibabacloud.com/help/doc-detail/25434.htm?spm=a2c65.11461447.0.0.7dd84f51itlGPJ) and log in as the root user.

After logging in to your Ubuntu 16.04 instance, run the following command to update your base system with the latest available packages.

apt-get update -y

Installation of required packages

Before you can start, you need to install the Nginx, PostgreSQL and Python packages on your system. You can install everything with the following command.

apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx -y

Once all the packages are installed, you can proceed to configure the PostgreSQL database.

PostgreSQL settings

Next, you need to create a PostgreSQL database and user for your Django application.

First, log in to the PostgreSQL interactive session by running the following command.

sudo -u postgres psql

Then use the following command to create a PostgreSQL database and user for your Django project.

postgres=# CREATE DATABASE testproject;
postgres=# CREATE USER testuser WITH PASSWORD 'password'; 

Then set the default encoding to UTF-8, the default transaction isolation scheme to "read committed", and the time zone to UTC with the following command:

postgres=# ALTER ROLE testuser SET client_encoding TO 'utf8';
postgres=# ALTER ROLE testuser SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE testuser SET timezone TO 'UTC';

Then grant all permissions to the database and end the PostgreSQL session with the following command:

postgres=# GRANT ALL PRIVILEGES ON DATABASE testproject TO testuser;
postgres=#  \q

Create a Python virtual environment

Next, you need to create a Python virtual environment for your project. You can do this by installing the required packages in Python in your virtual environment.

First, upgrade pip and install the virtual environment with the following command.

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

Next, create a directory for your project.

mkdir ~/testproject
cd ~/testproject

Next, run the following command to create a Python virtual environment.

virtualenv testprojectenv

Create a testprojectenv directory under the testproject directory with the above command and install the local version of Python and the local version of pip.

Next, you need to install all the packages needed for your project.

First, start the virtual environment with the following command.

source testprojectenv/bin/activate

After enabling the virtual environment, install the Django, Gunicorn, and psycopg2 PostgreSQL adapters with the following commands.

(testprojectenv) root@mail:~/testproject# pip install django gunicorn psycopg2

output:

Installing collected packages: pytz, django, gunicorn, psycopg2
Successfully installed django-2.1.1 gunicorn-19.9.0 psycopg2-2.7.5 pytz-2018.5

Set up a new Django project

Next, you need to tell Django to install the records in your project directory. This can be done with the following command:

(testprojectenv) root@mail:~/testproject# django-admin.py startproject testproject ~/testproject

Next, you need to define the server IP address, database username, and password in the settings.py file.

(testprojectenv) root@mail:~/testproject# nano /root/testproject/testproject/settings.py

Make the following changes:

ALLOWED_HOSTS = ['192.168.43.192']

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

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

Save and close the file when you are done.

Next, you need to migrate the initial database schema to the PostgreSQL database. This can be done by running the following script.

(testprojectenv) root@mail:~/testproject# ~/testproject/manage.py makemigrations
(testprojectenv) root@mail:~/testproject# ~/testproject/manage.py migrate

Then run the following command to create an admin user for your project.

(testprojectenv) root@mail:~/testproject# ~/testproject/manage.py createsuperuser

output:

Username (leave blank to use 'root'): 
Email address: [email protected]
Password: 
Password (again): 
Superuser created successfully.

Then run the following command to collect all static content in the directory location you set.

(testprojectenv) root@mail:~/testproject# ~/testproject/manage.py collectstatic

You can now start your Django development server and start your project with the following command:

(testprojectenv) root@mail:~/testproject# ~/testproject/manage.py runserver 0.0.0.0.0:8000

If the server starts successfully, you should see output similar to the following:

System check in progress ...

System check identified no issues (0 silenced).
September 10, 2018 - 15:06:07
Django version 2.1.1, using settings 'testproject.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

Now, open a web browser and enter the URL http://your-server-ip:8000. You'll be redirected to the Django index page as shown below.

image.png

You can also enter the URL http: // your-server-ip: 8000 / admin in your browser to access Django's admin interface. You will be prompted to enter the administrator username and password you created earlier, as follows:

image.png

After entering your username and password, click the login button. You'll be redirected to the Django admin screen as shown below.

image.png

Now press CTRL + C in the terminal window to shut down the development server.

If you want to test Gunicorn to test if it can serve your application, load the WSGI module of your project with the following command.

(testprojectenv) root@mail:~/testproject# gunicorn --bind 0.0.0.0:8000 testproject.wsgi

Running the above command will launch Gunicorn on the same interface that the Django development server was running on. You can access and test the URL [http: // your-server-ip: 8000](http: // your-server-ip: 8000 /? Spm = a2c65.11461447.0.0.7dd84f51ha1Xoz).

When the test is complete, press CTRL + C in the terminal to stop Gunicorn.

Then run the following command to deactivate the virtual environment.

(testprojectenv) root@mail:~/testproject# deactivate

Create a Systemd service file for Gunicorn

Next, create a systemd service file for Gunicorn. Now you can easily start and stop the application server. It is OK if you create the following file.

nano /etc/systemd/system/gunicorn.service

Add the following line.

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

[Service]
User=root
Group=www-data
WorkingDirectory=/root/testproject
ExecStart=/root/testproject/testprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/root/testproject/testproject.sock testproject.wsgi:application

[Install]
WantedBy=multi-user.target

Save and close the file. After that, start the Gunicorn service with the following command so that it can be started at startup.

systemctl start gunicorn
systemctl enable gunicorn

You can check the status of Gunicorn with the following command.

systemctl status gunicorn

Output.

  gunicorn.service - gunicorn daemon
   Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2018-09-10 20:58:14 IST; 10s ago
 Main PID: 2377 (gunicorn)
   CGroup: /system.slice/gunicorn.service
           ├─2377 /root/testproject/testprojectenv/bin/python3 /root/testproject/testprojectenv/bin/gunicorn --access-logfile - --workers 3 --b
           ├─2384 /root/testproject/testprojectenv/bin/python3 /root/testproject/testprojectenv/bin/gunicorn --access-logfile - --workers 3 --b
           ├─2385 /root/testproject/testprojectenv/bin/python3 /root/testproject/testprojectenv/bin/gunicorn --access-logfile - --workers 3 --b
           └─2386 /root/testproject/testprojectenv/bin/python3 /root/testproject/testprojectenv/bin/gunicorn --access-logfile - --workers 3 --b

Sep 10 20:58:14 mail.example.com systemd[1]: Started gunicorn daemon.
Sep 10 20:58:14 mail.example.com gunicorn[2377]: [2018-09-10 20:58:14 +0530] [2377] [INFO] Starting gunicorn 19.9.0
Sep 10 20:58:14 mail.example.com gunicorn[2377]: [2018-09-10 20:58:14 +0530] [2377] [INFO] Listening at: unix:/root/testproject/testproject.soc
Sep 10 20:58:14 mail.example.com gunicorn[2377]: [2018-09-10 20:58:14 +0530] [2377] [INFO] Using worker: sync
Sep 10 20:58:14 mail.example.com gunicorn[2377]: [2018-09-10 20:58:14 +0530] [2384] [INFO] Booting worker with pid: 2384
Sep 10 20:58:15 mail.example.com gunicorn[2377]: [2018-09-10 20:58:15 +0530] [2385] [INFO] Booting worker with pid: 2385
Sep 10 20:58:15 mail.example.com gunicorn[2377]: [2018-09-10 20:58:15 +0530] [2386] [INFO] Booting worker with pid: 2386

Set Nginx to Proxy Pass to Gunicorn

Gunicorn is now set up and working. Create a new Nginx configuration file in the etc / nginx / sites-available / directory.

nano /etc/nginx/sites-available/gunicorn

Add the following line.

server {
    listen 80;
    server_name 192.168.43.192;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /root/testproject;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/root/testproject/testproject.sock;
    }
}

Save and close the file. Then create a symbolic link to enable the Nginx virtual host.

ln -s /etc/nginx/sites-available/gunicorn /etc/nginx/sites-enabled/

Then test Nginx for misconfigurations with the following command:

nginx -t

It will be output.

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Finally, run the following command to restart Nginx.

systemctl restart nginx

Nginx is now configured to pass traffic to the process. To test, open a web browser and enter the URL [http://your-server-ip./?spm=a2c65.11461447.0.0.7dd84f51ha1Xoz). Then you will be redirected to the application as shown on the page below.

image.png

Recommended Posts

Set up Django on Ubuntu 16.04 with PostgreSQL and Gunicorn on ECS
Set up ansible-playbook on Ubuntu 20.04
Install Docker on Ubuntu and set up remote connection using tls
Set up ImpressPages 5.0 with LAMP on CentOS 7.3
Set up an SSH server on WSL2 Ubuntu 20.04
Steps to set up Postfix and Dovecot on CentOS 8.3
Install rbenv with apt on ubuntu and put ruby
Continuous integration on Alibaba Cloud ECS Ubuntu instance with Jenkins
Set up GitLab with docker
Set up Gitolite on CentOS 7
Set up a MineCraft Paper server on Ubuntu 20.04.1 LTS ② Update
Note: Install PostgreSQL 9.5 on Ubuntu 18.04
Install Cloud9 on Raspberry pi 4 and set up Rails development environment
How to install and use Composer on an ECS instance on Ubuntu 16.04
Install Ubuntu Server 20.04 in VirtualBox on Mac and connect with SSH
Install JDK and JRE on Ubuntu 16.10
[Ubuntu] Set up a Nukkit server
Enable Java 8 and Java 11 SDKs on Ubuntu
Install SonarQube on ECS instance on Ubuntu 16.04
Install ruby on Ubuntu 20.04 with rbenv
Installing and using Ansible on Ubuntu 16.04
Put Zabbix in Ubuntu with Docker and monitor Docker on the same host
Analyze and visualize csv logs with Excel Elastic Stack (docker-compose) --Set up with docker-compose
Notes on what to do when EC2 is set up with t2.micro
Building Rails 6 and PostgreSQL environment with Docker
DNS over HTTPS with Cloudflared on Ubuntu
How to set up and use kapt
Use cljstyle with Spacemacs on Ubuntu on WSL2
Set up Docker Registry locally on CentOS 7
Build OpenCV with Java Wrapper on Ubuntu 18.04
Run Ubuntu + ROS with Docker on Mac
Environment construction summary with rvm and postgresql
Set up Metabase service on Windows Server 2012
Monitor the Docker container and SystemD process on the same host with Zabbix on Ubuntu.
Introducing a dark Jupyter Notebook with pyenv and Vim keybindings on Ubuntu on WSL 2
How to set up computer vision for tracking images and videos with TrackingJs
Creating an SSL certificate using Let's Encrypt and setting up Nginx on Ubuntu 20