单机 Go 服务部署参考

发布时间:2019-10-12 20:08:40编辑:auto阅读(1389)

    笔者很想有 Go 的实战项目经验,无奈目前公司暂未给出实战机会,所以只得在自己的博客项目上折腾一番。之前博客是用 PHP 的 Laravel 写的,前段时间将其后端全部用 Go 重写了一遍,然后在部署上栽了坑。

    如果是单服务,在更新的过程中势必会出现服务不可用的状态。不像 PHP 这种无需编译的语言,直接将代码文件覆盖即可。

    只有一台服务器,那么就只能起两个或以上的服务,用 Nginx 来实现简单的负载均衡。

    Nginx 负载均衡配置

    upstream blog {
        server 127.0.0.1:8881;
        server 127.0.0.1:8882;
    }

    Supervisor 守护进程

    使用 supervisor 守护进程软件来管理服务,包括启动暂停重启等操作

    [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

    部署脚本

    部署脚本也很简单,总的思路就是循环关掉其中一个服务,更新,然后再重新开启。

    #!/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 即可。

    但是,由于 supervisor 目前使用的 3.3.4 及以下版本还不兼容 python3,所以如果服务器使用的是 python3,那么得先装个 python2.7 或更低版本的,然后用 python2.7 安装。

    此时如果服务器存在多个版本的 python,可以使用命令 python -m pip install supervisor 来指定 pip 使用的 python 版本。

关键字