用tsuru部署Python应用
概述
本文档是在tsuru中部署一个简单的Python应用的实战指南。例子应用是一个关联MySQL服务的很简单的Django项目。这些例子也适用于任何WSGI应用。
在tsuru中创建应用
使用app-create
命令创建应用:
$ tsuru app-create <app-name> <app-platform>
对于Python来说,应用平台是,你猜,python
!让我们脑洞打开,开发一个从未有人做过的教材应用:一个博客,而且它的名字也应该是很有创意,让我们叫他blog
:
$ tsuru app-create blog python
使用platform-list
命令列出所有的可用的平台。使用app-list
查看你所有的应用。
$ tsuru app-list
+-------------+-------------------------+--------------------------+
| Application | Units State Summary | Address |
+-------------+-------------------------+--------------------------+
| blog | 0 of 0 units in-service | blog.192.168.50.4.nip.io |
+-------------+-------------------------+--------------------------+
然后就可以发送你的应用代码了。
应用的代码
本文档不会专注于介绍如何用Django实现博客,你可以从GitHub clone整个源代码:https://github.com/tsuru/tsuru-django-sample。 下面是我们在项目中所做的事情:
. 创建项目 (django-admin.py startproject
). 启用django-admin. 安装South. 创建一个"posts"应用(django-admin.py startapp posts
). 为应用添加"Post"model. 在django-admin中注册该model. 用South进行数据库迁移
通过Git部署
在创建新的应用时,tsuru会显示应该使用的Git远程分支。用app-info
命令可以获得其信息:
$ tsuru app-info --app blog
Application: blog
Repository: git@192.168.50.4.nip.io:blog.git
Platform: python
Teams: admin
Address: blog.192.168.50.4.nip.io
Owner: admin@example.com
Team owner: admin
Deploys: 0
Pool: theonepool
App Plan:
+---------------+--------+------+-----------+--------+---------+
| Name | Memory | Swap | Cpu Share | Router | Default |
+---------------+--------+------+-----------+--------+---------+
| autogenerated | 0 MB | 0 MB | 100 | | false |
+---------------+--------+------+-----------+--------+---------+
Git远程分支被用来通过Git部署应用。当修改被推送到远程分支时,项目同时也被部署:
$ git push git@192.168.50.4.nip.io:blog.git master
Counting objects: 119, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (53/53), done.
Writing objects: 100% (119/119), 16.24 KiB, done.
Total 119 (delta 55), reused 119 (delta 55)
remote:
remote: ---> tsuru receiving push
remote:
remote: From git://cloud.tsuru.io/blog.git
remote: * branch master -> FETCH_HEAD
remote:
remote: ---> Installing dependencies
#####################################
# OMIT (see below) #
#####################################
remote: ---> Restarting your app
remote:
remote: ---> Deploy done!
remote:
To git@192.168.50.4.nip.io:blog.git
a211fba..bbf5b53 master -> master
如果遇到"Permission denied (publickey)."的错误,请确保你是团队一员并把公钥加到tsuru中。用key-add
命令添加公钥:
$ tsuru key-add mykey ~/.ssh/id_rsa.pub
使用git remote add
命令来避免每次push代码时都要输入整个远程仓库的链接:
$ git remote add tsuru git@192.168.50.4.nip.io:blog.git
然后运行:
$ git push tsuru master
Everything up-to-date
从此之后就可以省略掉—app
标记:
$ tsuru app-info
Application: blog
Repository: git@192.168.50.4.nip.io:blog.git
Platform: python
Teams: admin
Address: blog.192.168.50.4.nip.io
Owner: admin@example.com
Team owner: admin
Deploys: 0
Pool: theonepool
Units: 1
+------------+---------+
| Unit | State |
+------------+---------+
| eab5151eff | started |
+------------+---------+
App Plan:
+---------------+--------+------+-----------+--------+---------+
| Name | Memory | Swap | Cpu Share | Router | Default |
+---------------+--------+------+-----------+--------+---------+
| autogenerated | 0 MB | 0 MB | 100 | | false |
+---------------+--------+------+-----------+--------+---------+
列出依赖
在上一个部分我们忽略了部署过程的依赖。在tsuru中,一个应用可以有两种依赖:
- 操作系统级别的依赖, 以底层操作系统使用的包管理器为代表(比如:
yum
和apt-get
); - 平台依赖, 以平台/语言依赖的包管理工具为代表(在Python中是
pip
)。
所有的apt-get
依赖必须在requirements.apt
文件中指定,放在应用的根目录,同理,pip的依赖也必须放在应用根目录名为requirements.txt
的文件中。因为要用Django连接MySQL,我们需要用pip
安装mysql-python
,这个包依赖两个apt-get
包:python-dev
和libmysqlclient-dev
,因此requirements.apt
内容如下:
libmysqlclient-dev
python-dev
下面是requirements.txt
的内容:
Django==1.4.1
MySQL-python==1.2.3
South==0.7.6
请注意文件中也包含了South
,用于数据库移植,对于Django
应用,这是很常见的。下面是安装这些依赖的完整输出:
% git push tsuru master
#####################################
# OMIT #
#####################################
remote: Reading package lists...
remote: Building dependency tree...
remote: Reading state information...
remote: python-dev is already the newest version.
remote: The following extra packages will be installed:
remote: libmysqlclient18 mysql-common
remote: The following NEW packages will be installed:
remote: libmysqlclient-dev libmysqlclient18 mysql-common
remote: 0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
remote: Need to get 2360 kB of archives.
remote: After this operation, 9289 kB of additional disk space will be used.
remote: Get:1 http://archive.ubuntu.com/ubuntu/ quantal/main mysql-common all 5.5.27-0ubuntu2 [13.7 kB]
remote: Get:2 http://archive.ubuntu.com/ubuntu/ quantal/main libmysqlclient18 amd64 5.5.27-0ubuntu2 [949 kB]
remote: Get:3 http://archive.ubuntu.com/ubuntu/ quantal/main libmysqlclient-dev amd64 5.5.27-0ubuntu2 [1398 kB]
remote: debconf: unable to initialize frontend: Dialog
remote: debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
remote: debconf: falling back to frontend: Readline
remote: debconf: unable to initialize frontend: Readline
remote: debconf: (This frontend requires a controlling tty.)
remote: debconf: falling back to frontend: Teletype
remote: dpkg-preconfigure: unable to re-open stdin:
remote: Fetched 2360 kB in 1s (1285 kB/s)
remote: Selecting previously unselected package mysql-common.
remote: (Reading database ... 23143 files and directories currently installed.)
remote: Unpacking mysql-common (from .../mysql-common_5.5.27-0ubuntu2_all.deb) ...
remote: Selecting previously unselected package libmysqlclient18:amd64.
remote: Unpacking libmysqlclient18:amd64 (from .../libmysqlclient18_5.5.27-0ubuntu2_amd64.deb) ...
remote: Selecting previously unselected package libmysqlclient-dev.
remote: Unpacking libmysqlclient-dev (from .../libmysqlclient-dev_5.5.27-0ubuntu2_amd64.deb) ...
remote: Setting up mysql-common (5.5.27-0ubuntu2) ...
remote: Setting up libmysqlclient18:amd64 (5.5.27-0ubuntu2) ...
remote: Setting up libmysqlclient-dev (5.5.27-0ubuntu2) ...
remote: Processing triggers for libc-bin ...
remote: ldconfig deferred processing now taking place
remote: sudo: Downloading/unpacking Django==1.4.1 (from -r /home/application/current/requirements.txt (line 1))
remote: Running setup.py egg_info for package Django
remote:
remote: Downloading/unpacking MySQL-python==1.2.3 (from -r /home/application/current/requirements.txt (line 2))
remote: Running setup.py egg_info for package MySQL-python
remote:
remote: warning: no files found matching 'MANIFEST'
remote: warning: no files found matching 'ChangeLog'
remote: warning: no files found matching 'GPL'
remote: Downloading/unpacking South==0.7.6 (from -r /home/application/current/requirements.txt (line 3))
remote: Running setup.py egg_info for package South
remote:
remote: Installing collected packages: Django, MySQL-python, South
remote: Running setup.py install for Django
remote: changing mode of build/scripts-2.7/django-admin.py from 644 to 755
remote:
remote: changing mode of /usr/local/bin/django-admin.py to 755
remote: Running setup.py install for MySQL-python
remote: building '_mysql' extension
remote: gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
remote: In file included from _mysql.c:36:0:
remote: /usr/include/mysql/my_config.h:422:0: warning: "HAVE_WCSCOLL" redefined [enabled by default]
remote: In file included from /usr/include/python2.7/Python.h:8:0,
remote: from pymemcompat.h:10,
remote: from _mysql.c:29:
remote: /usr/include/python2.7/pyconfig.h:890:0: note: this is the location of the previous definition
remote: gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so
remote:
remote: warning: no files found matching 'MANIFEST'
remote: warning: no files found matching 'ChangeLog'
remote: warning: no files found matching 'GPL'
remote: Running setup.py install for South
remote:
remote: Successfully installed Django MySQL-python South
remote: Cleaning up...
#####################################
# OMIT #
#####################################
To git@192.168.50.4.nip.io:blog.git
a211fba..bbf5b53 master -> master
运行应用
如你所见,部署的输出信息中有一个步骤叫做"重启你的应用"。在这个步骤中,如果应用在运行,tsuru会重启它,如果没有运行,tsuru会启动它。但是tsuru是如何启动一个应用呢?非常简单,它使用了一个Procfile(从Foreman中偷学的概念)。这个Procfile用于描述应用如何被启动。我们可以使用gunicorn
去启动Django应用。如下是Procfile的内容:
web: gunicorn -b 0.0.0.0:$PORT blog.wsgi
现在我们提交文件并将其推送到tsuru的git服务器,再运行一次部署任务:
$ git add Procfile
$ git commit -m "Procfile: added file"
$ git push tsuru master
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 326 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
remote:
remote: ---> tsuru receiving push
remote:
remote: ---> Installing dependencies
remote: Reading package lists...
remote: Building dependency tree...
remote: Reading state information...
remote: python-dev is already the newest version.
remote: libmysqlclient-dev is already the newest version.
remote: 0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
remote: Requirement already satisfied (use --upgrade to upgrade): Django==1.4.1 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 1))
remote: Requirement already satisfied (use --upgrade to upgrade): MySQL-python==1.2.3 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 2))
remote: Requirement already satisfied (use --upgrade to upgrade): South==0.7.6 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 3))
remote: Cleaning up...
remote:
remote: ---> Restarting your app
remote: /var/lib/tsuru/hooks/start: line 13: gunicorn: command not found
remote:
remote: ---> Deploy done!
remote:
To git@192.168.50.4.nip.io:blog.git
81e884e..530c528 master -> master
现在我们碰到了一个错误:gunicorn: command not found
。这意味需要在requirements.txt
中添加gunicorn的依赖:
$ cat >> requirements.txt
gunicorn==0.14.6
^D
提交修改,再次运行部署:
$ git add requirements.txt
$ git commit -m "requirements.txt: added gunicorn"
$ git push tsuru master
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 325 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
remote:
remote: ---> tsuru receiving push
remote:
[...]
remote: ---> Restarting your app
remote:
remote: ---> Deploy done!
remote:
To git@192.168.50.4.nip.io:blog.git
530c528..542403a master -> master
应用部署成功,可以通过app-list
命令获得IP或者主机名,然后用浏览器去访问。比如,在下面的列表中:
$ tsuru app-list
+-------------+-------------------------+---------------------+
| Application | Units State Summary | Address |
+-------------+-------------------------+---------------------+
| blog | 1 of 1 units in-service | blog.cloud.tsuru.io |
+-------------+-------------------------+---------------------+
可以通过http://blog.cloud.tsuru.io/admin/ 访问应用的管理界面。
使用服务
既然gunicorn在运行,我们就能通过浏览器访问应用,此时会碰到一个Django的错误:"Can't connect to local MySQL server through socket'/var/run/mysqld/mysqld.sock' (2)"
。这个错误的意思是我们不能在本地访问MySQL。这是因为我们不应该在本地连接MySQL,必须要使用服务。服务的工作流分为下面两步:
. 创建一个服务的实例. 将服务的实例绑定到应用但是如何知道哪些服务是可用的呢?这很简单,运行service-list
命令:
$ tsuru service-list
+----------------+-----------+
| Services | Instances |
+----------------+-----------+
| elastic-search | |
| mysql | |
+----------------+-----------+
上面service-list
的输出说明有两个可用的服务:"elastic-search"和"mysql",并且没有实例。通过service-add
命令可以创建MySQL实例:
$ tsuru service-add mysql blogsql
Service successfully added.
现在,如果再次运行service-list
命令,可以从输出中看到新的服务实例:
$ tsuru service-list
+----------------+-----------+
| Services | Instances |
+----------------+-----------+
| elastic-search | |
| mysql | blogsql |
+----------------+-----------+
使用service-bind
命令将服务实例绑定到应用:
$ tsuru service-bind mysql blogsql
Instance blogsql is now bound to the app blog.
The following environment variables are now available for use in your app:
- MYSQL_PORT
- MYSQL_PASSWORD
- MYSQL_USER
- MYSQL_HOST
- MYSQL_DATABASE_NAME
For more details, please check the documentation for the service, using service-doc command.
从绑定的输出中我们看出,可以通过环境变量来连接MySQL服务器。下一步就是更新settings.py
去使用这些环境变量去连接数据库:
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get('MYSQL_DATABASE_NAME', 'blog'),
'USER': os.environ.get('MYSQL_USER', 'root'),
'PASSWORD': os.environ.get('MYSQL_PASSWORD', ''),
'HOST': os.environ.get('MYSQL_HOST', ''),
'PORT': os.environ.get('MYSQL_PORT', ''),
}
}
现在提交修改,再次运行部署:
$ git add blog/settings.py
$ git commit -m "settings: using environment variables to connect to MySQL"
$ git push tsuru master
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 535 bytes, done.
Total 4 (delta 3), reused 0 (delta 0)
remote:
remote: ---> tsuru receiving push
remote:
remote: ---> Installing dependencies
#####################################
# OMIT #
#####################################
remote:
remote: ---> Restarting your app
remote:
remote: ---> Deploy done!
remote:
To git@192.168.50.4.nip.io:blog.git
ab4e706..a780de9 master -> master
如果再次尝试访问管理页面,会碰到另一个错误:"Table 'blogsql.django_session' doesn't exist"
。嗯,这意味着我们已经连接到了数据库,绑定起作用了,但是还没有建立数据库。需要在远程服务器运行syncdb
和migrate
(如果使用South的话)。使用app-run
命令:
$ tsuru app-run -- python manage.py syncdb --noinput
Syncing...
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table south_migrationhistory
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.sessions
> django.contrib.sites
> django.contrib.messages
> django.contrib.staticfiles
> django.contrib.admin
> south
Not synced (use migrations):
- blog.posts
(use ./manage.py migrate to migrate these)
migrate
的使用类似.
部署钩子
每次部署后手动运行syncdb
或者migrate
会很烦人。所以我们可以配置一个自动的钩子,在每次应用重启前或者重启后运行。tsuru会解析一个名为tsuru.yaml
的文件,并重启的钩子。如扩展所建议的那样,这是一个YAML文件,包含了一系列在重启前后要运行的命令。下面是一个tsuru.yaml文件的例子:
hooks:
build:
- python manage.py syncdb --noinput
- python manage.py migrate
更多内容,请查看tsuru.yaml中的钩子文档部分。tsuru会在项目的根目录查找这个文件。让我们提交并且部署它:
$ git add tsuru.yaml
$ git commit -m "tsuru.yaml: added file"
$ git push tsuru master
Counting objects: 4, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 338 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
remote:
remote: ---> tsuru receiving push
remote:
remote: ---> Installing dependencies
remote: Reading package lists...
remote: Building dependency tree...
remote: Reading state information...
remote: python-dev is already the newest version.
remote: libmysqlclient-dev is already the newest version.
remote: 0 upgraded, 0 newly installed, 0 to remove and 15 not upgraded.
remote: Requirement already satisfied (use --upgrade to upgrade): Django==1.4.1 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 1))
remote: Requirement already satisfied (use --upgrade to upgrade): MySQL-python==1.2.3 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 2))
remote: Requirement already satisfied (use --upgrade to upgrade): South==0.7.6 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 3))
remote: Requirement already satisfied (use --upgrade to upgrade): gunicorn==0.14.6 in /usr/local/lib/python2.7/dist-packages (from -r /home/application/current/requirements.txt (line 4))
remote: Cleaning up...
remote:
remote: ---> Restarting your app
remote:
remote: ---> Running restart:after
remote:
remote: ---> Deploy done!
remote:
To git@192.168.50.4.nip.io:blog.git
a780de9..1b675b8 master -> master
顺利完成!现在我们有了一个部署在tsuru上,使用MySQL服务的Django项目,
进一步探索
更多信息,可以查看tsuru文档
,或者阅读tsuru命令完全使用指南。