[PYTHON] Deploy Django apps on Ubuntu + Nginx + MySQL (Build)

I signed a contract with GMO Cloud ALTUS and deployed the developed Django application to the environment of Nginx + uWSGI + MySQL + Python3, so I would like to keep a memorandum of the executed operation. Please note that this is just a work note and not necessarily a best practice. Please do not hesitate to point out any mistakes or shortages (laughs)

Operating environment

First, WSGI (Web Server Gateway Interface) is a standard interface (PEP333) between an application written in Python and a web server, and uWSGI refers to a web server that can run a web application that complies with the WSGI specifications.

The application created with Django is designed to work with WSGI and can be operated with various configurations, but this time Yuri Umezaki of Pycon 2015 announced (Web service operation using uWSGI / Docker) Example) was built with the following configuration.

--GMO Cloud ALTUS Basic Plan

Application configuration

Web Browser <--> Nginx <--> socket <--> uWSGI <--> Djnago <--> MySQL

Directory structure

/
└── var/
    └── www/
        └── example.jp/           <-Deployment destination folder
            ├── venv/             <-Virtual environment directory
            │   ├── app           <-Django application project root(django-Created with admin startproject app)
            │   │   └ main        <-Application root for Django applications(python manage.py startapp main)
            │   ├── uwsgi.ini     <-INI file that manages uwsgi startup options
            │   └── uwsgi_params  <-File that stores uwsgi variables
            └── static            <-Directory for storing static files

Server initialization

1. Firewall settings


GMO Cloud ALTUS has a function that allows you to set the firewall from the screen, so GMO Cloud ALTUS Altus Basic Series Guide-Create a new security group Set according to make_security.html). First, only "22" and "80" opened ports.

2. Log in to the virtual server


GMO Cloud ALTUS-Create a virtual server with the Ubuntu template for the Basic plan. Once created, you can log in as the user "cloud". After creating the virtual server, the login password of the virtual server is displayed in the dialog. Make a note of it as you cannot see it on other screens.

3. Change SSH port and prohibit login by root user


The SSH port number "22" is often hacked, so change it from 22 to another number (2222 this time). Also, regarding password authentication by the root user, "PermitRootLogin prohibit-password" is in a state where it can not be done even by default, so the minimum required settings are completed, but just in case, SSH login by the root user is prohibited at all. To do.

# sshd_Edit config file
[cloud]$ sudo vi /etc/ssh/sshd_config
[sudo] password for cloud:          <-Enter password for cloud user

/etc/ssh/sshd_config


# What ports, IPs and protocols we listen for
-Port 22
+Port 2222
(Omission)

# Authentication:
(Omission)
-PermitRootLogin prohibit-password
+PermitRootLogin no

4. Restart the SSH service


Restart the SSH service for the changes so far to take effect.

[cloud]$ sudo service ssh restart

After rebooting, close port "22" in the firewall and open port "2222". Once you can open and close the port

--Deny connections on port "22" --Port "2222", cannot log in as root user --Port "2222", cloud user can log in

Make sure.

5. SSH connection with public key authentication


[Change SSH port and prohibit login by root user](# 3-Change ssh port and prohibit login by root user) prohibits direct login as root user and sets so that only general users can log in. I've changed it, but I'll set it to log in using public key authentication for more secure use.

For those who want to know about public key authentication, "Understanding public key authentication" -even beginners can understand it well! Please refer to the Web server operation course by VPS (2).

Also, I am using Tera Term as an SSH client, but for the setting method of public key authentication in Tera Term, SSH connection by public key authentication --How to use Tera Term / linux / tera-term-ssh-login-public-key /) and [SSH public key cryptography-public key authentication login with Tera Term](http://www.j-oosk.com/teraterm/authorized_keys/ Please refer to 306 /).

After completing the public key authentication settings in Tera Term according to the above link,

/etc/ssh/sshd_config


# Change to no to disable tunnelled clear text passwords
-#PasswordAuthentication yes
+PasswordAuthentication no

To edit.

After editing, restart the SSH service as in [4. Restarting the SSH service](# 4-Restarting the ssh service), and confirm that the authentication method has changed from password authentication to public key authentication. I will.

6. Update your package management system


apt-get is a command to operate and manage packages using the APT (Advanced Package Tool) library, which is a package management system for Debian-based distributions (Debian and Ubuntu), and includes the dependencies of the applications you want to install. You can install / uninstall with.

#Update the database that manages the package (do not update the package itself)
[cloud]$ sudo apt-get update

#Update installed packages
[cloud]$ sudo apt-get upgrade

reference: [Ubuntu] Install / uninstall / upgrade package with apt-get How to use apt-get apt-get --Package operation and management --Linux command APT HOWTO (Obsolete Documentation) Chapter 3-Package Management [Location and confirmation method of operation log of Ubuntu / apt command](http://linux.just4fun.biz/Ubuntu/apt%E3%82%B3%E3%83%9E%E3%83%B3%E3%83] % 89% E3% 81% AE% E6% 93% 8D% E4% BD% 9C% E3% 83% AD% E3% 82% B0% E3% 81% AE% E5% 9C% A8% E5% 87% A6 % E3% 81% A8% E7% A2% BA% E8% AA% 8D% E6% 96% B9% E6% B3% 95.html)

7. Change locale (language, etc.) for Japan


The default locale is for English-speaking countries, and messages and dates are displayed for English-speaking countries, so change the locale for Japan.

#Check the locale before the change
[cloud]$ locale

#Confirm that it is an English-speaking locale
[cloud]$ date
Fri Dec 16 10:01:01 JST 2016

#Install Japanese pack
[cloud]$ sudo apt-get install language-pack-ja

#Update locale
[cloud]$ sudo update-locale LANG=ja_JP.UTF-8

#OS restart
[cloud]$ sudo shutdown -r now

#Check the changed locale
[cloud]$ locale

#Confirm that it has changed to the Japanese-speaking locale
[cloud]$ date

8. Time synchronization


Ubuntu used ntpdate to synchronize the time until 15.04, but from 15.10 it uses the Systemd function to synchronize the time. By default, an NTP server called "ntp.ubuntu.com" is used for time synchronization, so change it to the NICT (National Institute of Information and Communications Technology) NTP server (ntp.nict.jp).

#Check the time synchronization settings
[cloud]$ systemctl -l status systemd-timesyncd

#Change the time acquisition destination
[cloud]$ sudo sed -i 's/#NTP=/NTP=ntp.nict.jp/g' /etc/systemd/timesyncd.conf

? #OS restart
? sudo shutdown -r now

#Restart the time synchronization service
[cloud]$ sudo systemctl restart systemd-timesyncd.service

#Check the time synchronization settings
[cloud]$ systemctl -l status systemd-timesyncd

#Display time
[cloud]$ date

※reference: Change the time adjustment settings on Ubuntu 16.04 and 15.10 systemd I don't know

Create Nginx user

Later, when installing Nginx, we will create a group called Nginx and a user who cannot log in called Nginx. Set the 100s group ID and user ID according to the allocation policy below.

Use range
System Administrator 0 - 99
System account 100 - 999
User account 1000 - 29999
Reservation 30000 - 59999
#Check used group ID
[cloud]$ cat /etc/group

#Create nginx group
[cloud]$ sudo groupadd -g [Group ID] nginx

#Check used user ID
[cloud]$ cat /etc/passwd

#Create an nginx user that belongs to the nginx group
[cloud]$ sudo useradd -g nginx -u [User ID] -d /nonexistent -s /bin/false nginx

Creating a shared user

Create an app user as the user who runs the application.

#Add app user
[cloud]$ sudo useradd app -g nginx

#Confirm app user
[cloud]$ sudo cat /etc/passwd

#Check the group to which the app user belongs
[cloud]$ sudo groups app

#Set password for app user
[cloud]$ sudo passwd app

#Confirm that you can switch to app user
[cloud]$ su app

#Log out from app user
[app]$ exit

Python settings

I would like to install and use the package independently for each project, instead of installing it globally. Since it seems that pyvenv can be used instead of virtualenv from Python 3.3, use pyvenv.

#Ubuntu 16 of GMO Cloud ALTUS.Python is already installed in the 04 template.
#Check the installed Python.
[cloud]$ python3 -V

#install pip
[cloud]$ sudo apt install python3-pip

#update pip
[cloud]$ pip3 install --upgrade pip

#Install pyvenv
[cloud]$ sudo apt install python3-venv

reference: Prepare Python3 development environment with pyenv and venv Notes on what I learned when I thought about using pyenv or virtualenv on Windows

Nginx settings

Later, I would like to speed up and optimize the website, so this time I will use the PageSpeed module (ngx_pagespeed) developed by Google by incorporating it into Nginx. Install Nginx + ngx_pagespeed from source using a shell script provided by Google.

#Install unzip command
[cloud]$ sudo apt-get install unzip

#Install OpenSSL library
[cloud]$ sudo apt-get install libssl-dev

#PCRE library is a regular expression library
#Matching by regular expression will be possible by specifying URL rewrite and Location
[cloud]$ sudo apt-get install libpcre3-dev

#Create a cache destination directory for the buffer
[cloud]$ sudo mkdir -p /var/cache/nginx/client_temp

#Change the owner of the buffer cache destination directory
[cloud]$ sudo chown nginx:root /var/cache/nginx/client_temp

#Change the permissions of the buffer cache destination directory
[cloud]$ sudo chmod 700 /var/cache/nginx/client_temp

#Switch to root user
[cloud]$ sudo su -

#Latest Nginx and PageSpeed modules(ngx_pagespeed)Install
[root]$ bash <(curl -f -L -sS https://ngxpagespeed.com/install) --nginx-version latest -b /usr/local/src

#A dialog will appear in the middle where you can specify additional configure options, so specify additional options.
(Omission)
About to build nginx.  Do you have any additional ./configure
arguments you would like to set?  For example, if you would like
to build nginx with https support give --with-http_ssl_module
If you don't have any, just press enter.
> --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-file-aio --with-threads --with-ipv6 --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_ssl_module --with-cc-opt='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,--as-needed'

#Log out from root user
[root]$ exit

#Check Nginx version
[cloud]$ nginx -V

#Start Nginx
[cloud]$ sudo nginx

After starting Nginx, connect to http: // [IP address] with a browser, and if you can display the Nginx Welcome page, it's OK!

I will introduce the setting of ngx_pagespeed in the operation section that will be updated later, but this time I would like to check only the part that enables the function for the time being.

Add the setting to enable PageSpeed to the server directive in /etc/nginx/nginx.conf. In the server directive of nginx.conf

/etc/nginx/nginx.conf


http {
    (Omission)
    server {
         (Omission)
+        pagespeed on;
+        pagespeed RewriteLevel CoreFilters;
+        pagespeed FileCachePath /var/cache/ngx_pagespeed_cache;
+        pagespeed EnableFilters collapse_whitespace,trim_urls,remove_comments;
         (Omission)
    }

}

If you can add, restart Nginx and check the response of the request. If there is "X-Page-Speed: 1.11.33.4-0" in the response header, it's OK!

#Restart Nginx
[cloud]$ sudo nginx -s reload

#Throw a request and check the response header
[cloud]$ curl -I 'http://localhost/' | grep X-Page-Speed
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
X-Page-Speed: 1.11.33.4-0

reference: Build ngx_pagespeed From Source How to speed up your website by introducing Nginx + PageSpeed (ngx_pagespeed) 1st serialization of nginx: Introduction of nginx Use PageSpeed to optimize and speed up your website NGINX-1.5.12. Compile and install procedure [Debian] [CentOS] [Ubuntu] Check user ID policies and allocation rules Ubuntu Policy Manual - 9.2.2 UID and GID classes

MySQL settings

# MySQL5.Install 7
$ sudo apt-get -y install mysql-server-5.7

#Login as root user
$ mysql -u root -p

#Create database
mysql> CREATE DATABASE `[Database name]` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

#Select mysql database
mysql> USE 'mysql';

#Display user information
mysql> select user,host from mysql.user;

#Permission to user created & created database(CREATE, ALTER, REFERENCES, INDEX, SELECT, UPDATE, INSERT, DELETE)Grant
mysql> GRANT CREATE,ALTER,REFERENCES,INDEX,SELECT,UPDATE,INSERT,DELETE ON [Database name].* TO '[username]'@'localhost' IDENTIFIED BY '[password]';

#Check the permissions of the created user
mysql> SHOW GRANTS for '[username]'@'localhost';

#Log out of MySQL
mysql> exit

※reference MySQL installation Using MySQL with Django - Access denied for user '@'localhost [MySQL / User and DB Creation](http://wiki.minaco.net/index.php?MySQL%2F%E3%83%A6%E3%83%BC%E3%82%B6%E3%81%A8DB % E4% BD% 9C% E6% 88% 90)

Create a deployment destination directory

#Create a deployment destination directory
[cloud]$ sudo mkdir -p /var/www/example.jp

#Change the owner of the destination directory
[cloud]$ sudo chown root:nginx /var/www/example.jp

#Change the permissions of the deployment destination directory
[cloud]$ sudo chmod g+w /var/www/example.jp

#Switch to app user
$ su app

#Create a virtual environment called venv.
[app]$ /usr/bin/pyvenv /var/www/example.jp/venv

#Activate the created virtual environment. When the virtual environment is enabled, "([evn name])Is added to the beginning of the shell.
[app]$ source /var/www/example.jp/venv/bin/activate

#Update pip in virtual environment to the latest
(venv)[app]$ pip install --upgrade pip

#Install Django in a virtual environment
(venv)[app]$ pip install Django

#Install uWSGI in virtual environment
(venv)[app]$ pip install uwsgi

#Install PyMySQL in a virtual environment so you can connect to MySQL from Django
(venv)[app]$ pip install PyMySQL

#Disable the virtual environment once
(venv)[app]$ deactivate

I think there are various ways to deploy the created Django application, such as using Git or FTP software, but this time I will upload it to the server using FTP software.

Upload the created Django application as an app user under "/var/www/example.jp/venv/" with FTP software. However, I changed to prohibit password authentication in [SSH connection by public key authentication](# 5-ssh connection by public key authentication) and log in with public key authentication, so I set it so that public key authentication can also be performed with FTP software. Have to.

I use WinSCP as FTP software, but since WinSCP only supports PuTTY format private keys, I created it with [SSH connection by public key authentication](# 5-ssh connection by public key authentication). I converted the private key to PuTTY format.

Click the edit button from the login screen to display the "Advanced site settings" screen. Click "SSH" ⇒ "Authentication" in the navigation, and click the "Select File" button for "Private Key". The "Select Private Key" screen will appear. [SSH Connection by Public Key Authentication](# 5-When you select the private key created by ssh connection by public key authentication), it is automatically converted to the private key in PuTTY format.

uWSGI settings

#Log out from app user
[app]$ exit

#Create a directory to store uWSGI socket and pid files
[cloud]$ sudo mkdir -p /var/run/uwsgi

#Change the owner of the directory that stores uWSGI socket and pid files
[cloud]$ sudo chown root:nginx /var/run/uwsgi

#Change the permissions of the directory that stores uWSGI socket and pid files
[cloud]$ sudo chmod g+w /var/run/uwsgi

#Create a directory to store uWSGI log files
[cloud]$ sudo mkdir -p /var/log/uwsgi

Create a file (uwsgi_params) that defines variables for uWSGI under /var/www/example.jp/venv/.

/var/www/example.jp/venv/uwsgi_params


uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;

uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  REQUEST_SCHEME     $scheme;
uwsgi_param  HTTPS              $https if_not_empty;

uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

Create uwsgi.ini with uWSGI startup options.

vim:/var/www/example.jp/venv/uwsgi.ini


[uwsgi]
uid = nginx
gid = nginx

# Django-related settings
# the base directory (full path)
#Please change it according to your environment
chdir = /var/www/example.jp/venv/app

# Django's wsgi file
#Please change it according to your environment(Basically, "Django project name.wsgi "set)
module = app.wsgi

# the virtualenv (full path)
#Please change it according to your environment
home = /var/www/example.jp/venv


# process-related settings
# master
master = true

# maximum number of worker processes
processes = 2

threads = 1

# the socket (use the full path to be safe
socket = /var/run/uwsgi/master.sock

pidfile = /var/run/uwsgi/master.pid

# ... with appropriate permissions - may be needed
chmod-socket = 666

# clear environment on exit
vacuum = true

thunder-lock = true

max-requests = 6000
max-requests-delta = 300

# log
logto = /var/log/uwsgi/uwsgi.log
deamonize = /var/log/uwsgi/uwsgi-@(exec://date +%Y-%m-%d).log
log-reopen = true

Nginx settings

In the future, set the virtual host assuming that multiple applications will be operated on the same server.

Create directories "/ etc / nginx / sites-available" and "/ etc / nginx / sites-enabled" The virtual host configuration file is stored in "/ etc / nginx / sites-available".

When Nginx starts, read under "/ etc / nginx / sites-enabled", and in "/ etc / nginx / sites-enabled", symbolic link to the configuration file under "/ etc / nginx / sites-available" You can enable or disable the virtual host settings by adding or deleting them, which makes management easier.

#Create a directory to store the virtual host configuration file
[cloud]$ sudo mkdir /etc/nginx/sites-available

#Create a directory to store symbolic links to the configuration files for the virtual host you want to enable
[cloud]$ sudo mkdir /etc/nginx/sites-enabled

Create a virtual host configuration file under "/ etc / nginx / sites-available /".

/etc/nginx/sites-available/example.jp


# the upstream component nginx needs to connect to
upstream django {
    # for a file socket
    server unix:///var/run/uwsgi/master.sock;
}

# configuration of the server
server {
    # the port your site will be served on
    listen      80;
    # the domain name it will serve for
    # substitute your machine's IP address or FQDN
    server_name [IP address or domain];
    charset     utf-8;

    # max upload size
    # Django media
    location /static {
        # your Django project's static files - amend as required
        #Please change it according to your environment.
        alias /var/www/example.jp/static;
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        # the uwsgi_params file you installed
        #Please change it according to your environment.
        include     /var/www/example.jp/venv/uwsgi_params;
    }
}

After creating the virtual host configuration file, make a symbolic link.

#Make a symbolic link to the configuration file of the virtual host you want to enable
[cloud]$ sudo ln -s /etc/nginx/sites-available/example.jp /etc/nginx/sites-enabled/example.jp

Add to the http directive to read under "/ etc / nginx / sites-enabled /".

/etc/nginx/nginx.conf


http {
     (Omission)
     #gzip  on;
+    include /etc/nginx/sites-enabled/*;
     (Omission)
}

Set Nginx to start automatically even if the OS is restarted. Create "/etc/systemd/system/nginx.service".

/etc/systemd/system/nginx.service


[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Once you have created "/etc/systemd/system/nginx.service"

#Nginx is running, so stop
#If you get an error such as "Unable to open PID file", restart the OS
[cloud]$ sudo nginx -s stop

#Service start
[cloud]$ sudo systemctl start nginx

#Service outage
[cloud]$ sudo systemctl stop nginx

#Enable automatic service startup
[cloud]$ sudo systemctl enable nginx

#Service start
[cloud]$ sudo systemctl start nginx

After confirming that the service can be started / stopped by executing, register Nginx as a service.

Other commands for the service


#Service restart
$ sudo systemctl restart [Service name]

#Disable automatic service startup
$ sudo systemctl disable [Service name]

#Check the operating status of the service
$ sudo systemctl status [Service name]

#Kill all processes included in the service
$ sudo systemctl kill -s9 [Service name]

reference: [Introduce lightweight and high-speed web server Nginx to Ubuntu 12.04 (setting part 1)](http://blog.kondoyoshiyuki.com/2012/12/09/setting-1-nginx-on-ubuntu-12 -04 /) NGINX systemd service file

Django defaults

I want to create a database and tables in MySQL, so I'm going to do a Django DB migration.

#Enable virtual environment
[app]$ source /var/www/example.jp/venv/bin/activate

#Create migration file
(venv)[app]$ python /var/www/example.jp/venv/pornstar/manage.py makemigrations app

#Confirm the migration to be executed in SQL format
(venv)[app]$ python /var/www/example.jp/venv/pornstar/manage.py sqlmigrate app 0001

#Perform migration
(venv)[app]$ python /var/www/example.jp/venv/pornstar/manage.py migrate

Also, static files are collected by copying them from each application to a specific directory so that they can be easily published in the production environment. Copy the static file to the directory specified in with the following command.

Edit settings.py in your Django application, add STATIC_ROOT, and comment out STATICFILES_DIRS.

diff:/var/www/example.jp/venv/app/app/settings.py


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
+STATIC_ROOT = '/var/www/example.jp/static/'
(Omission)
-STATICFILES_DIRS = (
-    os.path.join(BASE_DIR, "static"),
-)
+#STATICFILES_DIRS = (
+#    os.path.join(BASE_DIR, "static"),
+#)
#Copying static files
(venv)[app]$ python /var/www/example.jp/venv/app/manage.py collectstatic

#Disable virtual environment
(venv)[app]$ deactivate

reference: How to publish static files

uWSGI auto-start settings

Like Nginx, create "/etc/systemd/system/uwsgi.service" so that uWSGI will start automatically even if the OS is restarted.

/etc/systemd/system/uwsgi.service


# uwsgi.service
[Unit]
Description=uWSGI
After=syslog.target

[Service]
ExecStartPre=/bin/bash -c 'mkdir -p /var/run/uwsgi; chown root:nginx /var/run/uwsgi; chmod g+w /var/run/uwsgi;'
ExecStart=/bin/bash -c 'source /var/www/example.jp/venv/bin/activate; uwsgi --ini /var/www/example.jp/venv/uwsgi.ini'
#Restart=always
Restart=on-failure
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target

"ExecStartPre" is an option to specify the command to be executed before starting the service, but it is specified to create the directory (/ var / run / uwsgi) to store the uWSGI pid file and socket file as the command to be executed.

Because "/ var / run" is a symbolic link to "/ run", and "/ run" is mounted on the tmpfs filesystem. Then, when the OS is restarted, all the files under "/ run (= / var / run)" will be deleted, so the command to create the directory is specified in case the directory does not exist.

Make sure you can start / stop the service and enable automatic startup.

#Service start
[cloud]$ sudo systemctl start uwsgi

#Service outage
[cloud]$ sudo systemctl stop uwsgi

#Enable automatic service startup
[cloud]$ sudo systemctl enable uwsgi

#Service start
[cloud]$ sudo systemctl start uwsgi

Update Django config file

diff:/var/www/example.jp/venv/app/app/settings.py


(Omission)
# SECURITY WARNING: don't run with debug turned on in production!
-DEBUG = True
+DEBUG = False
-ALLOWED_HOSTS = []
+ALLOWED_HOSTS = ['IP address or domain']
(Omission)

If you can access http: // [IP address or domain] with a browser and display the application, it's OK!

When it doesn't work

--Internal Error

Check the Nginx error log file (/var/log/nginx/error.log) and the uWSGI log file (/var/log/uwsgi/uwsgi.log) to identify the error.

References

  1. Incorporate uWSGI + Django app into Nginx
  2. Try nginx + uWSGI + Flask
  3. Procedures to publish Django app on CentOS 7 + Nginx
  4. How to use Django with uWSGI
  5. Django Best Practices-Deployment-Servers
  6. [Django environment construction (Ubuntu Server, Apache, PostgreSQL)](http://yura2.hateblo.jp/entry/2015/04/05/Django%E3%81%AE%E7%92%B0%E5 % A2% 83% E6% A7% 8B% E7% AF% 89 (Ubuntu_Server, _Apache, _PostgreSQL))
  7. From Apache installation to Django deployment
  8. Let's use uWSGI, a convenient and super powerful WSGI server
  9. Note that I deployed the Python Flask app under nginx + uWSGI environment
  10. Setting up Django and your web server with uWSGI and nginx

Recommended Posts

Deploy Django apps on Ubuntu + Nginx + MySQL (Build)
Deploy Django (Ubuntu 14.04 LTS + Nginx + uWSGI + Supervisor)
Build Python + django + nginx + MySQL environment using docekr
Build a Django environment on Raspberry Pi (MySQL)
build Python on Ubuntu
Deploy a Django application on EC2 with Nginx + Gunicorn + Supervisor
Deploy your Django application on Heroku
Build Python 3.8 + Pipenv environment on Ubuntu 18.04
Build wxPython on Ubuntu 20.04 on raspberry pi 4
# 3 Build a Python (Django) environment on AWS EC2 instance (ubuntu18.04) part2
Build Python3 and OpenCV environment on Ubuntu 18.04
Deploy the Django app on Heroku [Part 2]
Deploy the Django app on Heroku [Part 1]
Build your Django app on Docker and deploy it to AWS Fargate
Build NGINX + NGINX Unit + MySQL environment with Docker
Build Django + NGINX + PostgreSQL development environment with Docker
Build python environment with pyenv on EC2 (ubuntu)
Build Python3.5 + matplotlib environment on Ubuntu 12 using Anaconda
[Latest] How to build Java environment on Ubuntu
Run Python web apps on NGINX + NGINX Unit + Flask
(Case) Django (DRF) + uWSGI + Nginx + MySQL docker-compose.yml sample
Build a Kubernetes environment for development on Ubuntu
How to build Java environment on Ubuntu (Linux)
Django Heroku Deploy 1
Shebang on Ubuntu 20.04
Django Heroku Deploy 2
To you who are cornered by deploying Django. Django 2.2 deployment full version on Ubuntu 18.04 + Nginx
Django + MySQL settings
Deploy a Python 3.6 / Django / Postgres web app on Azure
Build a Django development environment using pyenv-virtualenv on Mac
# 2 Build a Python environment on AWS EC2 instance (ubuntu18.04)
How to deploy a Django application on Alibaba Cloud
Deploy a Django application on Google App Engine (Python3)
How to build a Django (python) environment on docker
Try running a Django application on an nginx unit
Build a Python virtual environment using venv (Django + MySQL ①)
Deploy a Django app made with PTVS on Azure