笔者很想有 Go 的实战项目经验,无奈目前公司暂未给出实战机会,因此只得在本身的博客项目上折腾一番。以前博客是用 PHP 的 Laravel 写的,前段时间将其后端所有用 Go 重写了一遍,而后在部署上栽了坑。python
若是是单服务,在更新的过程当中势必会出现服务不可用的状态。不像 PHP 这种无需编译的语言,直接将代码文件覆盖便可。linux
只有一台服务器,那么就只能起两个或以上的服务,用 Nginx 来实现简单的负载均衡。nginx
upstream blog { server 127.0.0.1:8881; server 127.0.0.1:8882; }
使用 supervisor 守护进程软件来管理服务,包括启动暂停重启等操做shell
[program:blogapi1] directory=/var/www/api.xfly.one/s1 command=/var/www/api.xfly.one/s1/production-blog autostart=true autorestart=true startsecs=5 user=root redirect_stderr=true stdout_logfile=/var/log/supervisord/blogapi1.log [program:blogapi2] directory=/var/www/api.xfly.one/s2 command=/var/www/api.xfly.one/s2/production-blog autostart=true autorestart=true startsecs=5 user=root redirect_stderr=true stdout_logfile=/var/log/supervisord/blogapi2.log
部署脚本也很简单,总的思路就是循环关掉其中一个服务,更新,而后再从新开启。vim
#!/bin/bash make SERVER_IP="xfly@127.0.0.1" SERVER_DIR="/var/www/api.xfly.one" for i in 1 2 do ssh $SERVER_IP "supervisorctl stop blogapi$i" scp production-blog $SERVER_IP:$SERVER_DIR/s$i ssh $SERVER_IP "supervisorctl start blogapi$i" done echo "deploy completed..."
对应的 Makefile 代码以下:后端
all: production local: gotool go build -v . production: gotool GOOS=linux GOARCH=amd64 go build -o production-blog -v . clean: rm -f blog rm -f production-blog find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} gotool: gofmt -w . go tool vet . 2>&1 | grep -v vendor;true help: @echo "make - compile the source code" @echo "make clean - remove binary file and vim swp files" @echo "make gotool - run go tool 'fmt' and 'vet'" .PHONY: clean gotool help
通常安装 supervisor 直接使用 pip install supervisor
或者使用 easy_install supervisor
便可。api
可是,因为 supervisor 目前使用的 3.3.4 及如下版本还不兼容 python3,因此若是服务器使用的是 python3,那么得先装个 python2.7 或更低版本的,而后用 python2.7 安装。bash
此时若是服务器存在多个版本的 python,能够使用命令 python -m pip install supervisor
来指定 pip 使用的 python 版本。服务器