From installing Flask on CentOS to making it a service with Nginx and uWSGI

A story about myself, who is ignorant of CentOS and Web server construction, set foot on Flask, Nginx, and uWSGI. The procedure is summarized here.

[](A separate article about the various hardships that occurred in the process ↓)

Premise

Preparation

Character

You should replace it as appropriate and read it.

ʻUser: username proj: project directory test.py`: Write code to run Flask. Placed directly under proj

Work is always done under the project directory

$ cd /home/user/proj

Introducing Flask

Use Flask to create an environment that makes it easy to create web applications in Python.

Install Python3

$ sudo yum install epel-release  #Put the repository
$ sudo yum install python3-devel  #Insert python3

Create a virtual environment

$ pip3 install pipenv  #Introduced pipenv
$ export PIPENV_VENV_IN_PROJECT=true  #Set to create a virtual environment in the project directory
$ pipenv --python 3  #Creating a virtual environment
$ ls -a  #Check the file list

If you can confirm that .venv is created, it's OK.

Installation of required modules

This is the minimum required.

$ pipenv install flask markupsafe

If you don't want to worry about migration, install with pipenv instead of pip. If you have other required modules, install them with pipenv install as well.

Try using Flask

Write Flask

Create test.py.

$ vi test.py

Enter the insert mode with ʻi and write the following. When you finish writing, exit with ʻEsc: wq.

test.py


from flask import *

app = Flask(__name__)

@app.route("/")
def main():
    return 'Hello, World!\n'

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=80)

It is a code that only outputs'Hello, World!'When the top page is accessed.

Run Flask

No matter how many modules you install, it doesn't start without entering the virtual environment.

$ pipenv shell  #Enter the virtual environment

Run test.py!

$ python test.py

Use a browser such as Google Chrome to enter the IP address of the server that executed this to access it. When "Hello, World!" Is displayed, it's OK. Return to the terminal and press Ctrl + C to stop execution.

Introducing Nginx

Introduction of Web server using Nginx. [](If you are already using Apache etc. and want to take this opportunity to break away from Apache here.)

Nginx installation

First, open nginx.repo with vim etc.

$ sudo vi /etc/yum.repos.d/nginx.repo

Describe the following.

nginx.repo


[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

Open HTTP port

Set the firewall to allow HTTP services.

$ sudo firewall-cmd --add-service=http --zone=public --permanent
$ sudo firewall-cmd --reload

Start Nginx

$ sudo systemctl start nginx  #Immediate start
$ lsof -i:80  #OK if nginx is displayed

Introduction of uWSGI

uWSGI is an application server that acts as an intermediary between Flask and Nginx.

uWSGI installation

$ pipenv install uwsgi

Creating a configuration file

$ vi test_uwsgi.ini

Describe the following.

test_uwsgi.ini


[uwsgi]
base = /home/user/proj
app = test
module = %(app)
virtualenv = /home/user/proj/.venv
pythonpath = %(base)
socket = /tmp/test_uwsgi.sock
chmod-socket = 666
callable = app
logto = /home/user/proj/log/%n.log

If you want to arrange it yourself ↓ Summary of uWSGI ini file

Also create a directory for logs.

$ mkdir log

Nginx side settings

Create a configuration file for Nginx under the proj directory.

$ vi test_nginx.conf

Describe the following.

test_nginx.conf


server {
  listen      80;
  server_name [IP address];
  charset     utf-8;

  location / { try_files $uri @yourapplication; }
  location @yourapplication {
    include uwsgi_params;
    uwsgi_pass unix:/tmp/test_uwsgi.sock;
  }
}

Place a symbolic link so that Nginx can refer to it at startup.

sudo ln -s /home/user/proj/test_nginx.conf /etc/nginx/conf.d/

Be sure to specify it with an absolute path.

(Optional) Disable SELinux

SELinux seems to constantly monitor and control access inside Linux. To minimize the damage when it is invaded by a PC. If you get an error when starting Nginx, you may be able to solve it by doing the following.

$ setenforce 0

This turns off access control. It seems that just going into Permissive mode does not mean that it will be completely turned off.

Edit the configuration file itself so that it will not be restored even if you restart.

$ vi /etc/selinux/config  # "SELINUX=enforcing"To"SELINUX=permissive"Rewrite to

Is security safe without using SELinux? It's good to use it, but I concluded that it's okay if you set the firewall firmly.

uWSGI operation check

$ sudo systemctl restart nginx  #You may get an error here if you don't turn off SELinux
$ uwsgi --ini test_uwsgi.ini  #Start uWSGI from the configuration file

Reload the browser and if'Hello, World!'Is displayed, it's OK.

Service conversion

Make these start automatically when the server starts.

Create a configuration file for uWSGI services

vi /etc/systemd/system/uwsgi.service

Describe the following.

uwsgi.service


[Unit]
Description=uWSGI
After=syslog.target

[Service]
ExecStart=/home/user/proj/.venv/bin/uwsgi --ini /home/user/proj/test_uwsgi.ini
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target
$ cat /lib/systemd/system/nginx.service  #OK if the one you just wrote is displayed

Service settings

$ sudo systemctl daemon-reload  # uwsgi.Reload service
$ sudo systemctl enable uwsgi nginx  #Enable uWSGI and Nginx services

Try restarting the server and check with your browser. If "Hello, World!" Is displayed, it's OK. Thank you for your hard work! !!

reference

-Until Hello World with Flask + uWSGI + Nginx @ Sakura's VPS (CentOS 6.6) -ConoHa VPS (CentOS 7.6) with Flask + Nginx + uWSGI Web application (multiple) execution environment construction -Hello World with Nginx and uWSGI -UWSGI setting memo when operating properly

Recommended Posts

From installing Flask on CentOS to making it a service with Nginx and uWSGI
Build a flask app made with tensorflow and dlib to work on centos7
A memo with Python2.7 and Python3 on CentOS
Run Flask on CentOS with python3.4, Gunicorn + Nginx.
Set up a yum repository server on CentOS7 system and refer to it locally and from other servers.
Output log to console with Flask + Nginx on Docker
API with Flask + uWSGI + Nginx
Connect to centos6 on virtualbox with ssh connection from Mac
Until Hello World with Flask + uWSGI + Nginx @ Sakura's VPS (CentOS 6.6)
I made a server with Python socket and ssl and tried to access it from a browser
Steps to set up Pipenv, create a CRUD app with Flask, and containerize it with Docker
Building a Python development environment on Windows -From installing Anaconda to linking Atom and Jupyter Notebook-
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
The road to installing Python and Flask on an offline PC
Create a Python3.4 + Nginx + uWSGI + Flask Web application execution environment with haste using pyenv on Ubuntu 12.04
Everything from building a Python environment to running it on Windows
I want to pass an argument to a python function and execute it from PHP on a web server
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
2. Make a decision tree from 0 with Python and understand it (2. Python program basics)
Deploy a Python app on Google App Engine and integrate it with GitHub
Make a decision tree from 0 with Python and understand it (4. Data structure)
Create a decision tree from 0 with Python and understand it (5. Information Entropy)
Make Jupyter Notebook a service on CentOS
Connecting from python to MySQL on CentOS 6.4
Create a web service with Docker + Flask
Story of making a virtual planetarium [Until a beginner makes a model with a script and manages to put it together]
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
A story about trying to install uwsgi on an EC2 instance and failing
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
Let's make an A to B conversion web application with Flask! From scratch ...
The road to fighting the connection between Nginx, Django and uwsgi and winning a little
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I want to write an element to a file with numpy and check it.
I tried running Flask on Raspberry Pi 3 Model B + using Nginx and uWSGI
WEB scraping with python and try to make a word cloud from reviews
Load a photo and make a handwritten sketch. With zoom function. Tried to make it.
Until you install Python with pythonbrew and run Flask on a WSGI server
A memorandum to make WebDAV only with nginx
Build a python environment with ansible on centos6
Hello World with nginx + uwsgi + python on EC2
Launch a web server with Python and Flask
Boot CentOS 8 from Windows 10 with Wake On LAN
How to set a shared folder with the host OS in CentOS7 on VirtualBOX
From the initial state of CentOS8 to running php python perl ruby with nginx
Control music playback on a smartphone connected to Raspberry Pi 3 and bluetooth with AVRCP
Steps to attach and debug from VS Code to Jupyter Lab on a remote server
Perform a Twitter search from Python and try to generate sentences with Markov chains.
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
A simple system that automatically shoots with object detection and sends it to LINE
I made a web application that maps IT event information with Vue and Flask
It was a little difficult to do flask with the docker version of nginx-unit
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Steps to quickly create a deep learning environment on Mac with TensorFlow and OpenCV
Until you create a machine learning environment with Python on Windows 7 and run it
Memo A beginner tried to build a Java environment and Japaneseize it on Ubuntu 18.04.2 LTS.
A high school student created a real-time language conversion service and pushed it to Github.
When plotting time series data and getting a matplotlib Overflow Error
Make a decision tree from 0 with Python and understand it (4. Data structure)
From installing Flask on CentOS to making it a service with Nginx and uWSGI
Python-Read data from a numeric data file and calculate covariance
Create a decision tree from 0 with Python and understand it (3. Data analysis library Pandas edition)
Get an image from a web page and resize it
Read the function name from the DB and execute it dynamically
Create a temporary file with django as a zip file and return it
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
The procedure from generating and saving a learning model by machine learning, making it an API server, and communicating with JSON from a browser
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
Try making a simple website with responder and sqlite3
I want to transition with a button in flask