Skip to content

Instantly share code, notes, and snippets.

@jankuo
Forked from wynemo/nginx.conf
Last active October 10, 2015 02:07
Show Gist options
  • Save jankuo/3615495 to your computer and use it in GitHub Desktop.
Save jankuo/3615495 to your computer and use it in GitHub Desktop.
tornado supervisor ubuntu12.04
# -*- coding:utf-8 -*-
import sys, os
import logging
import logging.config
import tornado
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
from tornado.options import define, options, parse_command_line
define('port', default=8000, help='run on the given port', type=int)
define('host', default='127.0.0.1', help='The host')
define('debug', default=False, type=bool)
define('log_config', default='logging.cfg', help='The logging config file')
os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'
path = os.path.dirname(os.path.abspath(__file__))
if path not in sys.path:
sys.path.insert(0, path)
def log_request(handler):
if handler.get_status() < 400:
log_method = logging.info
elif handler.get_status() < 500:
log_method = logging.warning
else:
log_method = logging.error
request_time = 1000.0 * handler.request.request_time()
log_method("%d %s %.2fms", handler.get_status(),
handler._request_summary(), request_time)
class MainHandler(tornado.web.RequestHandler):
def get(self):
return "Hello World!"
def start_service():
parse_command_line()
logging.config.fileConfig(options.log_config)
logging.info('Starting Tornado web server on http://%s:%s',
options.host, options.port)
settings = {
'debug': options.debug,
'log_function': log_request,
'address': options.host,
}
application = tornado.web.Application([
(r"/", MainHandler),
], **settings)
server_settings = {
'xheaders' : True,
}
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container, xheaders=True)
http_server.listen(options.port,'127.0.0.1')
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
start_service()
[formatters]
keys=detailed
[handlers]
keys=console
[loggers]
keys=root
[formatter_detailed]
format=%(name)s:%(levelname)s %(module)s:%(lineno)d: %(message)s
[handler_console]
class=StreamHandler
args=[]
formatter=detailed
[logger_root]
level=NOTSET
handlers=console
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
use epoll;
}
http {
types_hash_bucket_size 64;
# Enumerate all the Tornado servers here
upstream frontends {
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
server 127.0.0.1:8004;
}
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
keepalive_timeout 65;
proxy_read_timeout 200;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
gzip on;
gzip_min_length 1000;
gzip_proxied any;
gzip_types text/plain text/html text/css text/xml
application/x-javascript application/xml
application/atom+xml text/javascript;
# Only retry if there was a communication error, not a timeout
# on the Tornado server (to avoid propagating "queries of death"
# to all frontends)
proxy_next_upstream error;
server {
listen 80;
# Allow file uploads
client_max_body_size 50M;
location static/ {
root /srv/www/tornadotest/;
if ($query_string) {
expires max;
}
}
location = /favicon.ico {
rewrite (.*) /static/favicon.ico;
}
location = /robots.txt {
rewrite (.*) /static/robots.txt;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://frontends;
}
}
}
# https://gist.github.com/2422960/ copyright by orignal author
# Supervisord auto-start
#
# description: Auto-starts supervisord
# processname: supervisord
# pidfile: /var/run/supervisord.pid
SUPERVISORD=/usr/local/bin/supervisord
SUPERVISORCTL=/usr/local/bin/supervisorctl
case $1 in
start)
echo -n "Starting supervisord: "
$SUPERVISORD
echo -n "supervisord started"
echo
;;
stop)
echo -n "Stopping supervisord: "
$SUPERVISORCTL shutdown
echo
;;
restart)
echo -n "Restarting supervisord: "
$SUPERVISORCTL reload
echo
;;
esac
;partial supervisord.conf
[program:app]
process_name = main-%(process_num)s
command = python /srv/www/domain.com/tornado-linode/main.py
--port=%(process_num)s
--log_file_prefix=%(here)s/logs/%(program_name)s-%(process_num)s.log;要执行的命令,这里的“%(process_num)s”会用进程号替换,例如,第一个进程是8001,第二个进程是8002,以此类推,下同。
process_name=%(program_name)s-%(process_num)s ;process_name expr (default %(program_name)s) ;启动的进程的名字,这里的名字只是supervisor内部是别用,与你所启动程序的进程名无关
numprocs=4 ; 启动几个tornado进程
numprocs_start = 8000
directory=/home/wwwroot/app ; 运行前cd到此目录
autostart=true ; supervisord守护程序启动时自动启动tornado
autorestart=true ; supervisord守护程序重启时自动重启tornado
user=www-data ; 运行程序前su到此用户
redirect_stderr=true ; 将stderr重定向到stdout
stdout_logfile=/home/wwwroot/logs/tornado-80%(process_num)02d.log 记录控制台输出的日志位置
stderr_logfile=/sites/app1/logs/app1err.log ; 记录出错日志记录位置
stopsignal=QUIT
stdout_logfile_maxbytes=500MB
stdout_logfile_backups=50
stdout_capture_maxbytes=1MB
stdout_events_enabled=false
loglevel=warn

####install pip and virtualenv

$ sudo aptitude install python-setuptools python-pip
$ sudo pip install virtualenv

#easy_install
#easy_install pip
#pip install everything

####virtualenv and tornado stuff

$ cd webpy_project_dir
$ virtualenv --no-site-packages env
$ virtualenv --relocatable env
$ . env/bin/activate
$ pip install tornado torndb
$ pip install other_library

####nginx config

$ sudo aptitude install nginx
$/etc/init.d/nginx start

####supervisor config

$ sudo pip install supervisor
# cp /usr/local/lib/python2.7/dist-packages/supervisor/skel/sample.conf  /etc/supervisord.conf  #copy sample config
# supervisord
# vim /etc/supervisord.conf
# supervisorctl update   #after /etc/supervisord.conf
# supervisorctl start app1
# supervisorctl stop app1

###add supervisor to /etc/init.d/

# cp supervisord.sh /etc/init.d/supervisor
# chmod +x /etc/init.d/supervisor
# /usr/sbin/update-rc.d -f supervisor defaults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment