来源引用:
关于 Gunicorn 和 Nginx
####Gunicorn Gunicorn is a stand-alone WSGI web application server which offers a lot of functionality. It natively supports various frameworks with its adapters, making it an extremely easy to use drop-in replacement for many development servers that are used during development.
Technically, the way Gunicorn works is very similar to the successful Unicorn web server for Ruby applications. They both use what's referred to as the pre-fork model. This, in essence, tasks the central [Gunicorn] master process to handle the management of workers, creation of sockets and bindings, etc.
####Gunicorn Server Highlights
- Runs any WSGI Python web application (and framework)
- Can be used as a drop-in replacement for Paster (Pyramid), Django's Development Server, web2py etc.
- Comes with various worker types and configurations
- Manages worker processes automatically
- HTTP/1.0 and HTTP/1.1 (Keep-Alive) support through synchronous and asynchronous workers
- Supports SSL
- Extensible with hooks
- Python 2.6+ and 3.x support
Web Application Deployment Using Nginx
Nginx is a very high performant web server / (reverse)-proxy. It has reached its current popularity due to being light weight, relatively easy to work with, and easy to extend (with add-ons / plug-ins). Thanks to its architecture, it is capable of handling a lot of requests (virtually unlimited), which - depending on your application or website load - could be really hard to tackle using some other, older alternatives.
Remember: "Handling" connections technically means not dropping them and being able to serve them with something. You still need your application and database functioning well in order to have Nginx serve clients *esponses that are not error messages.
#####为什么把Nginx作为反向代理放在应用服务器前面 Why use Nginx as a reverse-proxy in front of an application server?
Many frameworks and application servers (including Gunicorn) can serve static files (e.g. javascript, css, images etc.) together with responses. However, the better thing to do is to let a (reverse-proxy) server such as Nginx handle the task of serving these files and managing connections (requests). This relieves a lot of the load from the application servers, granting you a much better overall performance.
As your application grows, you will want to optimize it— and when the time comes, distribute it across servers (VPS) to be able to handle more connections simultaneously (and have a generally more robust architecture). Having a reverse-proxy in front of your application server(s) helps you with this from the very beginning.
Nginx's extensibility (e.g. native caching along with failover and other mechanisms) is also a great feat that benefits web applications unlike (simpler) application servers.
#####Example of a Basic Server Architecture:
Client Request ----> Nginx (Reverse-Proxy) | /|\
| |-> App. Server I. 127.0.0.1:8081 |
--> App. Server II. 127.0.0.1:8082 `----> App. Server III. 127.0.0.1:8083
###Preparing Your Droplet for Production 怎么翻译这句?
要做以下三个工作:
- 升级操作系统
- 下载安装 通用python工具。(pip, virtualenv)
- 一个虚拟的环境包含应用程序
Updating the default operating system
For Debian Based Systems (i.e. Ubuntu, Debian), run the following:
aptitude update
aptitude -y upgrade
For RHEL Based Systems (i.e. CentOS), run the following:
yum -y update
Setting up Python, pip and virtualenv
On Ubuntu and Debian, a recent version of Python interpreter which you can use comes by default. It leaves us with only a limited number of additional packages to install:
- python-dev (development tools), aptitude install python-dev
- pip (to manage packages), aptitude install python-pip
- virtualenv (to create isolated, virtual environments). pip install virtualenv
一个自我包含的python虚拟环境Creating a self-contained Virtual (Python) Environment
mkdir my_app
cd my_app
virtualenv my_app_env(如果使用python3,要先apt-get install python3 virutal -a /usr/bin/python3 my_app_env)
mkdir app
source my_app_venv/bin/activate
最后,要部署的目录为下面的结构:
my_app # Main Folder to Contain Everything Together | |=== my_app_venv # V. Env. folder with the Python Int. |=== app # Your application module |.. |.
下载安装Gunicorn
建议把所有应用程序需要的内容全部放到虚拟环境下。因此,我们在虚拟环境中安装Gunicore
pip install gunicorn
下载安装Nginx
所有安装默认为Debian系统。 aptitude install nginx
运行: sudu service nginx start
停止: sudu service nginx stop
使用gunicorn服务 python web applications
####WSGI WSGI简要说,这个是Web服务器和应用程序之间的接口。它存在是确保在不同的服务器和应用程序之间能够依照严格的标准相互工作。不管是在应用程序和产品环境中都每个部件都是可以交换的。
####WSGI 应用程序对象(可调用的):wsgi.py
my_app # Main Folder to Contain Everything Together | |=== my_app_venv # V. Env. folder with the Python Int. |=== app # Your application module | |--- wsgi.py # File containing application callable |.. |.
运行the server
gunicorn -b 0.0.0.0:8080 wsgi &
还可以使用nohup 命令 让程序在后台执行。> https://www.ibm.com/developerworks/cn/linux/l-cn-nohup/ nohup gunicorn --worker-class=gevent NSLoger.wsgi:application -b 127.0.0.1:8000&
**注意**如果你使用参数 -b 127.0.0.1 不会被外部的IP访问到。
配置优化 Gunicorn
关于更多配置:http://docs.gunicorn.org/en/latest/deploy.html#nginx-configuration 编写配置文件:
workers = 4
bind = ‘127.0.0.1:8000′
proc_name = ‘app’
pidfile = ‘/tmp/app.pid’
执行:
gunicorn --config gunicorn.conf app:app
As mentioned earlier, Gunicorn is highly configurable and it is very easy to modify all necessary parameters to have it your way.
[!] Important: All settings and configuration options listed below are to be chained (put one after the other) to launch gunicorn and to server your application. You cannot modify any of the options after launching the server. Whichever option or option(s) you use, they must be followed by the wsgi file containing the point of entry to your application.
# Simply running the server (as shown above):
gunicorn -b 0.0.0.0:8080 wsgi
# Running the server with five workers:
gunicorn -b 0.0.0.0:8080 --workers=5 wsgi
工人数 通常,工人数被认为和I/O能力绑定而不是和CPU绑定。这就是说瓶颈来自于磁盘。当一个工作进程(a worker)在忙于磁盘操作,另外一个在使用cpu优化请求。
# (2 Workers * CPU Cores) + 1
# ---------------------------
# For 1 core -> (2*1)+1 = 3
# For 2 cores -> (2*2)+1 = 5
# For 4 cores -> (2*4)+1 = 9
You can specify the amount of workers by passing the argument --workers=[n].
Usage:
# Example: gunicorn --workers=[number of workers]
gunicorn --workers=5
Socket Settings
The way socket bindings work is as follows:
# Example: gunicorn -b [address:port]
gunicorn -b 127.0.0.1:8080
Note: When an application is set to listen for incoming connections on 127.0.0.1, it will only be possible to access it locally. If you use 0.0.0.0, however, it will accept connections from the outside as well.
Selecting The Worker Type Usage:
# Example: gunicorn -k [worker]
gunicorn -k sync # or;
gunicorn -k gevent # ..
Available types:
- sync
- eventlet
- gevent
- tornado
**Number of Simultaneous Connections for Eventlet / Gevent **
To modify number of simultaneous connections for Eventlet and Gevent workers:
# Example: gunicorn -k [worker] --worker-connections [number]
gunicorn -k gevent --worker-connections 1001
**Access Logs **
If you would like to set explicitly the file to write access logs:
# Example: gunicorn --log-file [file]
gunicorn --log-file error_logs.log
Error Logs
In order to specify a file to write error logs to, use this setting.
# Example: gunicorn --access-logfile [file]
gunicorn --access-logfile acclogs
Log Level
This is used to set the granularity of error log outputs. Possible options are:
-
debug
-
info
-
warning
-
error
-
critical
-
Usage: ###配置Nginx Configuring Nginx
vim /etc/nginx/sites-available/default
server {
listen 80;
server_name www.isaced.com;
access_log /var/log/nginx/isaced.log;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
root /data/url; #Flask项目所在目录
}