# 记录一次服务器重新部署的经历（网站、gogs和一些脚本）


## 前言

前段时间由于手贱在服务器上跑爬虫，开了100个进程，内存和cpu双双达到极限值，第二天起来一看，性能曲线赛高，使用 putty 和网页版 ssh 登录服务器，被拒之门外。于是重启服务器，然后发现启动报错，找阿里云售后工程师，说部分关键文件丢失，这种情况无法正常启动，建议恢复快照…… 无奈，依次尝试恢复快照，结果发现只有一月份的快照是正常的…… 这意味着我没法把系统直接恢复到最近的正常状态，一些服务和程序需要我重新搭建一遍。

心情崩溃…… 好在网站有 [自动备份](http://yangyingming.com/article/359/)，阿里云也可以 从快照创建磁盘 ，这说明数据没有丢失，不幸中的万幸，然后只要花时间把服务和程序重新搭建起来就可以恢复之前的状态了。


**原系统：**  
ubuntu 14.04 LTS 32bit

**新系统：**   
ubuntu 16.04 LTS 64bit

## 创建新用户

创建新用户，不再用 root 直接运行程序。
```python
root@iZ2zegis1iqwk7ddw7voqtZ:~# useradd yym 		# 创建用户 yym
root@iZ2zegis1iqwk7ddw7voqtZ:~# passwd yym  		# 设置用户 yym 的密码
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
root@iZ2zegis1iqwk7ddw7voqtZ:~# visudo     		 # 添加用户 yym 使用 sudo 的权限
root@iZ2zegis1iqwk7ddw7voqtZ:~# cd /home    		# 跳转目录到 home
root@iZ2zegis1iqwk7ddw7voqtZ:/home# mkdir yym   	# 创建 yym 用户目录
root@iZ2zegis1iqwk7ddw7voqtZ:/home# su yym  		# 切换到用户 
```



## 挂载数据盘

新用户的数据都将放置在这个数据盘里

```python
yym@iZ2zegis1iqwk7ddw7voqtZ:/home$ sudo fdisk -l    # 查看所有磁盘
...
yym@iZ2zegis1iqwk7ddw7voqtZ:/home$ sudo mount /dev/vdb ~    # 挂载磁盘 /dev/vdb
```

**问题**：用新用户登陆后命令行只有一个$   
**原因**：/etc/passwd 中新建用户没有 bash 的权限   
**解决方法**：在新用户权限后添加 /bin/bash

参考资料：[Linux 格式化和挂载数据盘](https://help.aliyun.com/document_detail/25426.html?spm=5176.doc25446.2.3.ifWqWH)




## 修改 shell 默认配色

github上找到的配色解决方案，[dircolors-solarized](https://github.com/seebi/dircolors-solarized)

#### 1、将配色方案clone到本地
```python
git clone https://github.com/seebi/dircolors-solarized.git
```
（需要先安装git，没有安装的先在shell里运行命令apt-get install git）

#### 2、设置配色方案到 .dircolors

```python
cp dircolors.256dark ~/.dircolors
```
（需要先移动到dircolors-solarized目录下)

#### 3、重新登录用户

```python
eval `dircolors dircolors.256dark`
```
运行以上命令可以直接预览配色效果，但是下次登录会恢复默认配色

详情可参考：[改变linux默认配色方案（dircolors和dircolors-solarized使用）](http://yangyingming.com/article/22/)




## 在用户根目录下创建 .bashrc 和 .profile

.bashrc 和 .profile 是系统启动时自动运行的脚本，会自动运行一些配置，方便使用。

在配置之前，如果你是新用户，**首先要给新用户添加使用 bash 的权限**。
```python
sudo vi /etc/passwd
```
然后在新用户那一行最后添加 ```/bin/bash```：
```python
your_user:x:1000:1000::/home/whz:/bin/bash
```

创建 .bashrc 和 .profile 的方法有两个：
#### 方法一：
直接复制了 root 用户的 .bashrc 和 .profile 过来，并修改权限为当前用户。
```python
sudo cp /root/.profile ~
sudo cp /root/.bashrc ~
sudo chown user:user ~/.profile
sudo chown user:user ~/.bashrc
```

#### 方法二：
可以直接用别人造好的轮子，我选了一个，原因是安装方便：[fnichol/bashrc](https://github.com/fnichol/bashrc)。

执行以下命令即可：
```python
curl -L https://raw.githubusercontent.com/fnichol/bashrc/master/contrib/install-local | bash
```






## vim 配置
vim 我使用了 github 上 [ma6174/vim](https://github.com/ma6174/vim) 的配置，Star 数量 2.9k，搜索 vim 第一条结果就是。

安装十分简单，运行一条命令即可：

```python
wget -qO- https://raw.github.com/ma6174/vim/master/setup.sh | sh -x
```
**问题**：使用 vim 编辑 py 文件的时候出现如下错误：

```python
"ex.py" 5L, 87C
Error detected while processing /home/yym/.vim/ftplugin/python/pyflakes.vim:
line   28:
Error: the pyflakes.vim plugin requires Vim to be compiled with +python
Press ENTER or type command to continue
```
**解决方法**：   
链接：https://jingyan.baidu.com/article/3f16e00308b4482591c1030f.html

步骤：

去github重新下载一个pyflakes.vim：
```python
git clone --recursive git://github.com/kevinw/pyflakes-vim.git
```
将python目录下的所有文件复制到~/.vim/ftplugin目录下：
```python
cp -R ./pyflakes-vim/ftplugin/python/  ~/.vim/ftplugin/
```

**ma6174/vim 使用方法见链接**：   
https://github.com/ma6174/vim/blob/master/tips.md



## 添加 pip 豆瓣源加速安装

使用默认 pip 源安装各种 python 库速度十分慢，经常出现 read time out 超时错误。忍无可忍，换成国内的 pip 豆瓣源。

#### 临时使用豆瓣源

```python
sudo easy_install -i http://pypi.douban.com/simple/ saltTesting 
sudo pip install -i http://pypi.douban.com/simple/ saltTesting
```

#### 永久使用豆瓣源（linux）

```python
cd ~
mkdir .pip
vi .pip/pip.conf
```

添加内容
```python
[global] 
index-url = http://pypi.douban.com/simple 
trusted-host = pypi.douban.com
```

#### 永久使用豆瓣源（windows）
1. 在windows文件管理器中,输入 %APPDATA%
2. 会定位到一个新的目录下，在该目录下新建pip文件夹，然后到pip文件夹里面去新建个pip.ini文件
3. 在新建的pip.ini文件中输入以下内容，搞定文件路径："C:\Users\Administrator\AppData\Roaming\pip\pip.ini"
```python
[global]
timeout = 6000
index-url = http://pypi.douban.com/simple
trusted-host = pypi.douban.com
```

在用 pip 安装 python 库试试，速度是不是快多了呢？ :)

参考于：

[国内的pythoner强烈建议使用豆瓣的pypi源 zz](https://www.douban.com/note/302711300/)

[windows环境下永久修改pip镜像源的方法](https://blog.csdn.net/zheng_lan_fang/article/details/78612392)

## Ubuntu 添加 apt-get 国内源
#### 创建备份，修改 sources.list 文件
```python
cd /etc/apt
sudo cp sources.list sources.list.bak
sudo vi sources.list
```

#### 添加国内源
```python
# aliyun
deb http://mirrors.aliyun.com/ubuntu/ trusty main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-backports main restricted universe multiverse

# tsinghua
# The source image is annotated by default to improve apt update speed and can be 
# uncommented if necessary
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security main restricted universe multiverse

# Pre-release software source is not recommended
# deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-proposed main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-proposed main restricted universe multiverse

# ustc
deb http://debian.ustc.edu.cn/ubuntu/ trusty main multiverse restricted universe
deb http://debian.ustc.edu.cn/ubuntu/ trusty-backports main multiverse restricted universe
deb http://debian.ustc.edu.cn/ubuntu/ trusty-proposed main multiverse restricted universe
deb http://debian.ustc.edu.cn/ubuntu/ trusty-security main multiverse restricted universe
deb http://debian.ustc.edu.cn/ubuntu/ trusty-updates main multiverse restricted universe
deb-src http://debian.ustc.edu.cn/ubuntu/ trusty main multiverse restricted universe
deb-src http://debian.ustc.edu.cn/ubuntu/ trusty-backports main multiverse restricted universe
deb-src http://debian.ustc.edu.cn/ubuntu/ trusty-proposed main multiverse restricted universe
deb-src http://debian.ustc.edu.cn/ubuntu/ trusty-security main multiverse restricted universe
deb-src http://debian.ustc.edu.cn/ubuntu/ trusty-updates main multiverse restricted universe
```

#### 更新 apt-get
```python
sudo apt-get update
```

## 搭建个人博客 MingBlog 网站

###在 ubuntu 16.04 上安装 mysql-5.6


**安装 mysql 两篇教程**：   
https://askubuntu.com/questions/762384/install-mysql-5-6-on-ubuntu-16-04   
http://blog.csdn.net/keeyce/article/details/52217730

**启动 mysql**   
http://blog.csdn.net/he582754810/article/details/53516158

**允许远程用户登录访问 mysql**   
http://www.cnblogs.com/hyzhou/archive/2011/12/06/2278236.html

**mysql 数据库还原 gzip 备份文件**   
http://blog.csdn.net/junqing124/article/details/42869521

**完全卸载 mysql**  
http://www.linuxidc.com/Linux/2013-04/82934.htm



### 配置 nginx
#### 1.安装 nginx

```python
sudo apt-get install nginx
```
#### 2.查看 nginx 服务状态

```python
yym@iZ2zegis1iqwk7ddw7voqtZ:~ $ service nginx status
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2017-07-17 21:07:51 CST; 27s ago
 Main PID: 30583 (nginx)
   CGroup: /system.slice/nginx.service
           ├─30583 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
           └─30584 nginx: worker process
```
看到 active (running) 表示 nginx 服务已经启动

#### 3.添加 nginx 配置文件   
在 **/etc/nginx/conf.d/** 创建网站级配置文件 **MingBlog.conf**（.conf 后缀名一定要有） 
文件内容见下：

```python
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    # root /usr/share/nginx/html;
    #index index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    charset utf-8;

    # max upload size
    client_max_body_size 75M;

    # Django static
    location /static{
        # Django project's static files
        #expires 30d;
        #autoindex on;
        #add_header Cache-Control private;
        alias /home/yym/workspace/MingBlog/static/;
    }
    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        # try_files $uri $uri/ =404;
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
        root /home/yym/workspace/MingBlog;
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:8001;
        uwsgi_read_timeout 2;
    }
}
```



### 配置 uwsgi

#### 1.安装 uwsgi

```python
sudo apt-get install uwsgi
```

#### 2.查看 uwsgi 服务状态

```python
yym@iZ2zegis1iqwk7ddw7voqtZ:~ $ service uwsgi status
● uwsgi.service - LSB: Start/stop uWSGI server instance(s)
   Loaded: loaded (/etc/init.d/uwsgi; bad; vendor preset: enabled)
   Active: active (exited) since Mon 2017-07-17 21:17:00 CST; 29s ago
     Docs: man:systemd-sysv-generator(8)
```
看到 Active: active (exited) 表示服务已启动



### 安装 MingBlog 网站运行环境


**问题**：用原来的32位系统的 virtualenv 环境运行 uwsgi 会报以下错误：

```python
uwsgi: error while loading shared libraries: libexpat.so.1: cannot open shared object file: No such file or directory
```
**解决方法**：根据 requirements.txt 在新系统中重装一下网站运行环境环境：   

#### 1.准备

```python
sudo apt-get install virtualenv         # 安装 virtualenv
virtualenv --no-site-packages BLOG_VENV # 用 virtualenv 创建网站运行环境
source BLOG_VENV/bin/activate       # 激活 virtualenv 环境
```
**问题**：mysql-python 安装时报错 EnvironmentError: mysql_config not found   
**解决方法**：http://www.cnblogs.com/xiazh/archive/2012/12/12/2814289.html

#### 2.使用豆瓣源加速pip安装

```python
pip install -r ../BLOG_VENV_BACKUP/requirements.txt -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
```

新环境安装完毕，尝试运行 uwsgi，错误消失。

#### 3.修改博客系统的第三方库   
参考：http://www.yangyingming.com/article/360/



### 启动 MingBlog 网站
运行命令

```python
yym@iZ2zegis1iqwk7ddw7voqtZ:~/workspace/MingBlog$ ./uwsgiserver.sh start
```



## 搭建 gogs 私人 git 服务器

#### 1.搭建 gogs 服务

可参考：[使用 gogs 搭建私人 git 服务器 | nginx 添加反向代理到二级域名](http://yangyingming.com/article/383/)


#### 2.恢复 gogs 仓库数据  

由于 gogs 仓库信息有一些记录在数据库上，且 gogs 的数据库当时没有设置自动备份，这就导致我现在只有原来的仓库数据，但是数据库中没有这些仓库匹配的信息。

如何恢复仓库可以参考： [gogs: 如何恢复repository](http://www.cnblogs.com/ilovewindy/p/6700867.html)，亲测有效，就是麻烦了点，希望 gogs 官方早点集成恢复本地仓库功能。



## 恢复 cron 计划任务

放置 cron 计划任务清单的文件一般在 **/var/spool/cron** 下

将原来的清单中的任务复制到新清单中即可恢复


## 恢复 IPProxyPool 代理池服务

按照 [qiyeboy/IPProxyPool](https://github.com/qiyeboy/IPProxyPool) 提示安装依赖，然后运行命令启动即可。

为了方便使用，我在这里将 python 运行环境用 virtualenv 集成到项目中，然后提交到 gogs 私人 git 服务器中。觉得安装依赖麻烦的也可以这么做。

#### IPProxyPool 启动命令
```python
nohup ~/workspace/IPProxyPool/IPPROXYPOOL_VENV/bin/python ~/workspace/IPProxyPool/IPProxy.py > ~/workspace/log/IPProxyPool.log 2>&1 &
```

## 实现Python 3.6与2.7共存及版本切换（CentOS为例）
一般 linux 系统会自带 python 2，所以我们首先安装 python 3。

具体过程可以参考：
* [Linux下编译安装python3](https://www.cnblogs.com/freeweb/p/5181764.html)
* [CentOS 7中实现Python 3.6与2.7共存及版本切换](https://blog.csdn.net/lpwmm/article/details/80160242)

## 安装 shadowsocks 科学上网

```python
# 安装 shadowsocks
pip install shadowsocks
# 启动
nohup sslocal -c /etc/shadowsocks.json /dev/null 2>&1 &
echo " nohup sslocal -c /etc/shadowsocks.json /dev/null 2>&1 &" /etc/rc.local   #设置自启动
```

参考资料：
[CentOS 7 安装 shadowsocks 客户端](https://brickyang.github.io/2017/01/14/CentOS-7-%E5%AE%89%E8%A3%85-Shadowsocks-%E5%AE%A2%E6%88%B7%E7%AB%AF/)

## 原创声明

**转载请注明：[呓语](http://www.yangyingming.com) » [记录一次服务器重新部署的经历（网站、gogs和一些脚本）](http://www.yangyingming.com/article/390)**
