How to set up django nginx ubuntu 18.04.1?

How to set up django nginx ubuntu 18.04.1?


// Set up Ubuntu server 18.04
# create VM -
# Download iso from official site
# https://www.ubuntu.com/download/server
/* WARNING TERMINAL USAGE IS INVOLVED */
# Download the "Ubuntu Server 18.04.1 LTS - Long time support"
# Now download VirtualBox (or any other virtual machine thingie)
# download putty nad winscp (if windows) i don't actually know for Mac and linux,
# probnably use the terminal
# create a new virtual machine
  -> Storage (more than 10.0 GB)
  -> VHD - virtual hard disk
  -> GoTo settings>network>advanced(on the network adapter active)>portforwarding
  -> make a rule for http
    -> name  = "http"
    -> protocol = "TCP"
    -> Host IP = "127.0.1.1"
    -> Host Port = "8080"
    -> Guest IP = "10.0.2.15"
    -> Guest port = "8080" 
  -> make another rule for SSH
    -> name  = "SSH"
    -> protocol = "TCP"
    -> Host IP = "127.0.1.1"
    -> Host Port = "22"
    -> Guest IP = "10.0.2.15"
    -> Guest port = "22"
  -> GoTo settings>Storage>Controller: IDE
    -> add the iso you downloaded
    using [disk image]+ sign
# Start the virtual machine you just created
** In the virtual machine **
-> do a standard install
either use putty and winscp to edit files etc or just juntinue in the terminal if you want to
-> now when you are in your virtual machine
// To Updtate
=> sudo apt-get update
=> sudo apt-get upgrade
// If using python3
=> sudo apt-get install python3-pip django python3-dev libpq-dev postgresql postgresql-contrib nginx
=> pip3 install django
// if using python2
=> sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx
=> pip install django
// Create the PostgreSQL Database and User
=> sudo -u postgres psql
=> sudo su - postgres
=>  postgres@test-server:~$ createuser --interactive -P
    Enter name of role to add: db_user
    Enter password for new role:
    Enter it again:
    Shall the new role be a superuser? (y/n) n
    Shall the new role be allowed to create databases? (y/n) n
    Shall the new role be allowed to create more new roles? (y/n) n
->  Create Database for your project
=>  postgres@test-server:~$ createdb --owner db_user django_db;
=>  postgres@ubuntu:~$ logout
=>  sudo apt-get install python-virtualenv
// Create a virtual environment for your project
=>  $ virtualenv -p python3 django_env
        New python executable in django_env/bin/python
        Installing distribute..............done.
        Installing pip.....................done.
// activate your virtual enironment that you just made
=>  $ source django_env/bin/activate
->  Create a Project or import it from your pc usinig winscp
=>  django-admin.py startproject sample_project
=>  cd sample_project
// Do your migrations and stuff
=>  python manage.py runserver 0.0.0.0:8080
// so to install psycopg2
// First install dependencies
=>  (django_env) $ sudo apt-get install libpq-dev python3-dev
=>  (django_env) $ pip install psycopg2
-> Coonfigure the database in your settings.py file.
=>  DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'django_db',
            'USER': 'db_user',
            'PASSWORD': '<password you entered when creating db_user>',
            'HOST': 'localhost',
            'PORT': '', # default
        }
    }

=>  ALLOWED_HOSTS = ['127.0.1.1']  # your server's IP or domain name
//  do the migrations again.
//  install gunicorn
=>  (django_env) $ pip install gunicorn
=>  (django_env) $ gunicorn sample_project.wsgi:application --bind 0.0.0.0:8001
//  create a new file  named "gunicorn_start.bash"
=>  (django_env) $ vim gunicorn_start.bash
//  if you are comfortable using vim paste this into it
//  or just use winscp to edit it with other things such as visual studio
==> File start
#!/bin/bash

NAME="django_app"                                   # Name of the application
DJANGODIR=/home/ubuntu/sample_project               # Django project directory
SOCKFILE=/home/ubuntu/django_env/run/gunicorn.sock  # we will communicte using this unix socket
USER=ubuntu                                         # the user to run as
GROUP=ubuntu                                        # the group to run as
NUM_WORKERS=3                                       # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=sample_project.settings      # which settings file should Django use
DJANGO_WSGI_MODULE=sample_project.wsgi              # WSGI module name
echo "Starting $NAME as `whoami`"

# Activate the virtual environment

cd $DJANGODIR
source /home/ubuntu/django_env/bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

# Create the run directory if it doesn't exist

RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
  --name $NAME \
  --workers $NUM_WORKERS \
  --user=$USER --group=$GROUP \
  --bind=unix:$SOCKFILE \
  --log-level=debug \
  --log-file=-
==> File end
// To save and quit vim text editor
=>  :wq
// to make this script executable
=>  sudo chmod u+x gunicorn_start.bash
//  test it
=>  (django_env) $ ./gunicorn_start.bash
Starting hello_app as hello
2013-06-09 14:21:45 [10724] [INFO] Starting gunicorn 18.0
2013-06-09 14:21:45 [10724] [DEBUG] Arbiter booted
2013-06-09 14:21:45 [10724] [INFO] Listening at: unix:/webapps/hello_django/run/gunicorn.sock (10724)
2013-06-09 14:21:45 [10724] [INFO] Using worker: sync
2013-06-09 14:21:45 [10735] [INFO] Booting worker with pid: 10735
2013-06-09 14:21:45 [10736] [INFO] Booting worker with pid: 10736
2013-06-09 14:21:45 [10737] [INFO] Booting worker with pid: 10737
// If you see this you are good!
// Now install supervisor
=>  $ sudo apt-get install supervisor
// Now create a file named "sample_project.conf" in the given dir below
=>  $ sudo vim /etc/supervisor/conf.d/sample_project.conf
==> File start
[program:sample_project]
command = /home/ubuntu/gunicorn_start.bash                   ; Command to start app
user = ubuntu                                                ; User to run as
stdout_logfile = /home/ubuntu/logs/gunicorn_supervisor.log   ; Where to write log messages
redirect_stderr = true                                       ; Save stderr in the same log
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8              ; Set UTF-8 as default encoding
==> File end
// to save the logs to a file
=>  (django_env) $ mkdir -p /home/test-server/logs/
=>  (django_env) $ touch /home/test-server/logs/gunicorn_supervisor.log
=>  $ sudo supervisorctl reread
    sample_project: available
=>  $ sudo supervisorctl update
    sample_project: added process group
=>  $ sudo supervisorctl start sample_project
=>  $ sudo systemctl restart supervisor
=>  $ sudo systemctl enable supervisor
//  To check the status
=>  $ sudo supervisorctl status sample_project
//  To stop
=>  $ sudo supervisorctl stop sample_project
// or to restart
=>  $ sudo supervisorctl restart sample_project
// change the Coonfiguration file
=>  $ sudo vim /etc/nginx/sites-available/sample_project.conf
==> File start 
upstream sample_project_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).
  server unix:/home/ubuntu/django_env/run/gunicorn.sock fail_timeout=0;
}

server {

    listen   80;
    server_name test-server;

    client_max_body_size 4G;
    access_log /home/ubuntu/logs/nginx-access.log;
    error_log /home/ubuntu/logs/nginx-error.log;

    location /static/ {
        alias   /home/ubuntu/static/;
    }

    location /media/ {
        alias   /home/ubuntu/media/;
    }

    location / {

        # an HTTP header important enough to have its own Wikipedia entry:
        #   http://en.wikipedia.org/wiki/X-Forwarded-For
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


        # enable this if and only if you use HTTPS, this helps Rack
        # set the proper protocol for doing redirects:
        # proxy_set_header X-Forwarded-Proto https;

        # pass the Host: header from the client right along so redirects
        # can be set properly within the Rack application
        proxy_set_header Host $http_host;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;

        # set "proxy_buffering off" *only* for Rainbows! when doing
        # Comet/long-poll stuff.  It's also safe to set if you're
        # using only serving fast clients with Unicorn + nginx.
        # Otherwise you _want_ nginx to buffer responses to slow
        # clients, really.
        # proxy_buffering off;

        # Try to serve static files from nginx, no point in making an
        # *application* server like Unicorn/Rainbows! serve static files.
        if (!-f $request_filename) {
            proxy_pass http://sample_project_server;
            break;
        }
    }

    # Error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /home/ubuntu/static/;
    }
}
==> File end
// create an alias
=> $ sudo ln -s /etc/nginx/sites-available/sample_project.conf /etc/nginx/sites-enabled/sample_project.conf
=> $ sudo service nginx start

Comments

Popular posts from this blog

How to build unlimited levels menu through PHP and MySQL

How to build a map of the frequency with which characters occur in a file in OCaml?

How to create timed pop-up windows using MVVM?