前述

这里使用的阿里云服务器部署,云服务器ssh登陆成功后,如果几分钟没有操作的话,sshd会自动断开登陆,对于我们来说,在部署软件有时要等很久,经常会发生ssh断开的情况,又或是上个侧所回来ssh就断开了,非常头痛。

这里我们要先解决ssh断开连接的问题

# egrep ^Client /etc/ssh/sshd_config
ClientAliveInterval 15 --间隔多少秒发送一次心跳
ClientAliveCountMax 1800 --多少秒没有数据产生时断开连接

部署py3+uwsgi+nginx用于运行py3应用程序

部署Docker

  1. CentOS 7 安装Docker
    # yum -y install docker
    # echo 1 > /proc/sys/net/ipv4/ip_forward   --打开路由转发,用于给容器上外网
    # systemctl restart network

2、配置阿里Docker镜像源
如果直接使用DockerHub官方仓库上传下载镜像的话,网速不快,因为跨国了,这里使用国内的阿里Docker镜像源:
https://cr.console.aliyun.com/ ->登陆->管理中心->镜像加速(根据提示配置)

#  vi /etc/docker/daemon.json              --这是我机器的配置
{
  "registry-mirrors": ["https://uss01m1d.mirror.aliyuncs.com"]
}

#  systemctl daemon-reload
#  systemctl restart docker
#  docker pull centos:7

Docker里部署py3+uwsgi+nginx

1、运行docker容器

#  docker run --name py3 -v /data/:/www -p 172.18.108.136:80:80 --privileged -d centos7:py3  /usr/sbin/init

#  docker exec -it py3  bash     --登陆py3容器

2、编译安装python3.6
--安装前先安装依赖软件包

#  yum install wget openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel gcc-c++  libxml* gzip  zlib zlib-devel

--下载python3.6软件包

#  wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz

--解压编译

#  tar -zxvf Python-3.6.3.tar.gz  -C /usr/src/  
#  cd /usr/src/Python-3.6.3
#  ./configure --prefix=/usr/local/python3  && make && make install
#  ln -s /usr/local/python3/bin/python3.6 /usr/bin/python3
#  ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3

3、安装django和uwsgi

#  pip3 install django
#  pip3 install uwsgi

--安装的django 和 uwsgi 全部在python的安装目录下下
# ln -s /usr/local/python3/bin/uwsgi /usr/bin/uwsgi3

4、测试uwsgi

#  vim test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')]) 
    return [b"Hello World"]

--运行uwsgi3

#  uwsgi3 --http :80 --wsgi-file test.py
#  lsof -i:80
COMMAND  PID USER   FD  TYPE DEVICE SIZE/OFF NODE NAME
uwsgi3  1178 root   3u  IPv4 813312      0t0  TCP *:80 (LISTEN)

--uwsgi3已经监听80端口
访问http:// 172.18.108.136:80 可见Hello World。

--停止uwsgi3,释放80端口,测试django
# kill -9 1178

5、测试Django
--将django项目创建在/www/apply目录下

#  mkdir /www/apply  && cd /www/apply 

--创建django项目:webapp

#  python3 /usr/local/python/bin/django-admin.py startproject webapp

--运行python3

#  cd webapp/
#  python manage.py runserver 0.0.0.80

访问http:// 172.18.108.136:80 可见下图算成功
Docker手动构建 nginx+py3+uwsgi环境

如访问看到的是以下错误,则需要修改访问的权限

#  vi /www/apply/webapp/webapp/setti ngs.py
28  ALLOWED_HOSTS = ['*']      --在[]里加上*代表允许所有ip访问

Docker手动构建 nginx+py3+uwsgi环境

6、将uwsgi和django连接起来
前面uwsgi和django测试已经没问题,接下来将两个连起来

--确认80端口没有被占用
# uwsgi3 --http :80 --chdir /www/apply/webapp --module webapp.wsgi
备 –chdir 指定项目的绝对路径,--module 是指项目的wsgi模块

#  lsof -i:80
COMMAND  PID USER   FD  TYPE DEVICE SIZE/OFF NODE NAME
uwsgi3  1178 root   3u  IPv4 813312      0t0  TCP *:80 (LISTEN)

访问http:// 172.18.108.136:80 可见下图
代表uwsgi和django已经连起来
Docker手动构建 nginx+py3+uwsgi环境

附:启动uwsgi时需要加很多参数不方便记,我们可以参照官网写一个配置文件来启动

# cd /www/apply/webapp
# vim webapp.ini
[uwsgi]
# Django-related settings 
# the base directory (full path) 
chdir = /www/apply/webapp 

# Django's wsgi file 
module = webapp.wsgi 

# the virtualenv (full path) 
# home = /path/to/virtualenv 

# process-related settings 
# master master = true 

# maximum number of worker processes 
processes = 5

# the socket (use the full path to be safe) 
# socket = /path/to/your/project/mysite.sock 
socket = :81 

# ... with appropriate permissions - may be needed 
# chmod-socket = 664 

# clear environment on exit 
vacuum = true

启动时就改用webapp.ini来启动
# uwsgi3 --ini /www/apply/webapp/webapp.ini

部署nginx反向代理

1、编译安装nginx
--编译之前,先安装nginx软件所依赖的软件包

# yum install patch make cmake gcc gcc-c++ gcc-g77 flex bison file libtool libtool-libs autoconf kernel-devel libjpeg libjpeg-devel libpng libpng-devel libpng10 libpng10-devel gd gd-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glib2 glib2-devel bzip2 bzip2-devel libevent libevent-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel vim-minimal nano fonts-chinese gettext gettext-devel ncurses-devel gmp-devel pspell-devel unzip libcap diffutils pcre

# wget http://nginx.org/download/nginx-1.13.8.tar.gz
# tar -zxvf nginx-1.13.8.tar.gz  -C /usr/local
# cd /usr/local/nginx-1.13.8
# ./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-ipv6  &&  make  && make install

--停掉80端口,启动nginx,如没有报错,
打开浏览器: http:// 172.18.108.136:80 可见:Welcome to nginx

2、配置nginx代理uwsgi

#  vi /usr/local/nginx/conf/nginx.conf
    upstream webapp {         --该段添加在server{}外面,http{}里面
        server 127.0.0.1:81;      --uwsgi3服务器和监听的端口
    }
    server {
        listen 80;
        server_name webapp.com;
        charset utf-8;
        client_max_body_size 75M;       
        location / {
            include uwsgi_params
            uwsgi_pass webapp;
        }
    }

--启动uwsgi3监听81端口

# uwsgi3 --ini /www/apply/webapp/webapp.ini

# lsof -i:80
COMMAND  PID USER   FD  TYPE DEVICE SIZE/OFF NODE NAME
uwsgi3  1178 root   3u  IPv4 813312      0t0  TCP *:81 (LISTEN)

--启动nginx监听80端口

# /usr/local/nginx/sbin/nginx -t   --确定nginx没有报错

![](http://i2.51cto.com/images/blog/201804/15/430321341f62f458506e060fb2774147.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

# lsof -i:80
COMMAND  PID USER   FD  TYPE DEVICE SIZE/OFF NODE NAME
nginx   18535  root    6u  IPv4 842111      0t0  TCP *:http (LISTEN)
nginx   18536 nginx    6u  IPv4 842111      0t0  TCP *:http (LISTEN)

访问http:// 172.18.108.136:80 又看到django界面
代表nginx已经成功代理了uwsgi3
Docker手动构建 nginx+py3+uwsgi环境

3、配置MariaDB
--安装mariadb

# yum install mariadb mariadb-devel mariadb-server

--修改配置,将数据目录指向到/www/共享目录下

# vi /etc/my.cnf
[mysqld]
datadir=/www/MariaDB/mysql
socket=/www/MariaDB/mysql/mysql.sock
log-error=/www/MariaDB/log/mariadb.log
pid-file=/www/MariaDB/log/mariadb.pid
log-bin=mariadb-bin

# mkdir /www/MariaDB
# chown mysql.mysql -R /www/MariaDB

# systemctl restart mariadb
# ln -s /www/MariaDB/mysql/mysql.sock /var/lib/mysql/mysql.sock
# mysqladmin -u root password 123456

--创建user和database给django用

# mysql -uroot -p123456
MariaDB [(none)]> CREATE DATABASE webapp;
MariaDB [(none)]> show databases like 'webapp';
+----------------+
| Database        |
+----------------+
| webapp          |
+----------------+
1 rows in set (0.00 sec)

MariaDB [(none)]> grant all privileges on webapp.* to apply@'%' identified by 'apply';
MariaDB [(none)]> select host,user,password from mysql.user where user='apply';
+--------------+-------+-------------------------------------------+
| host          | user  | password                                     |
+--------------+-------+-------------------------------------------+
| %             | apply | *09B402E6D1FBDF77CD0F6F0CE586137BAD897877 |
+--------------+-------+-------------------------------------------+
1 rows in set (0.00 sec)

MariaDB [(none)]> exit;

4、创建django项目
--创建django项目,测试django连接MySQL

--安装连接mysql数据库插件

# pip install --allow-all-external mysql-connector-python
# vim /www/apply/webapp/webapp/settings.py
DATABASES = {
    'default': { 'ENGINE': 'mysql.connector.django',
    'NAME': 'webapp',
    'USER': 'apply',
    'PASSWORD': 'apply',
    }
}

--安装blog

# cd /www/apply/webapp/
# python3 manage.py startapp blog
# ls              --可以看到在webapp项目下已经有了一个blog文件夹
blog  manage.py  webapp

--修改settings.py 配置文件,添加blog应用

# vim webapp/settings.py
INSTALLED_APPS = ( 
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',    --添加此句
 )

--初始化blog数据库数据

# python3 manage.py migrate
Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions   
Running migrations:
    Applying contenttypes.0001_initial... OK
    Applying auth.0001_initial... OK
    Applying admin.0001_initial... OK
    Applying admin.0002_logentry_remove_auto_add... OK
    Applying contenttypes.0002_remove_content_type_name... OK
    Applying auth.0002_alter_permission_name_max_length... OK
    Applying auth.0003_alter_user_email_max_length... OK
    Applying auth.0004_alter_user_username_opts... OK
    Applying auth.0005_alter_user_last_login_null... OK
    Applying auth.0006_require_contenttypes_0002... OK
    Applying auth.0007_alter_validators_add_error_messages... OK
    Applying auth.0008_alter_user_username_max_length... OK
    Applying auth.0009_alter_user_last_name_max_length... OK
    Applying sessions.0001_initial... OK

--确认数据库webapp里已经生成了库表

# mysql -uroot -p123456
MariaDB [(none)]> use webapp
MariaDB [webapp]> show tables;
+----------------------------+
| Tables_in_webapp            |
+----------------------------+
| auth_group                  |
| auth_group_permissions     |
| auth_permission             |
| auth_user                   |
| auth_user_groups            |
| auth_user_user_permissions |
| django_admin_log            |
| django_content_type         |
| django_migrations           |
| django_session              |
+----------------------------+
10 rows in set (0.00 sec)

--创建登陆blog的帐号/密码

# python3 manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: root@mail.com
Password:    --输入密码
Password (again):    --再次输入
Superuser created successfully.

--启动uwsgi3,并访问blog论坛
# uwsgi3 --ini /www/apply/webapp/webapp.ini

--访问http:// 172.18.108.136/admin 能看到以下内容,代表已经搭建成功
Docker手动构建 nginx+py3+uwsgi环境

使用前面创建的帐号admin/admin123登陆,如登陆成功则表示成功连接上数据库
注:看到此界面没有任何的css样式和图片,接下来我们做静态图版的反向代理

5、nginx代理静态图片
前面我们已经访问到了blog,但没有css样式,这时我们在浏览器里按下F12->Network
Docker手动构建 nginx+py3+uwsgi环境

可以看到css的访问路径是http://localhost/static/admin/css 这个路径。
在webapp下新建static,然后nginx进行设置

# cd /www/apply/webapp
# mkdir static
# cp -fr /usr/local/python3/lib/python3.6/site-packages/django/contrib/admin/static/admin/ ./static/

--设置nginx代理static

#  vim /usr/local/nginx/conf/nginx.conf
 --在server{}里加入以下
        location /static {
            alias /www/apply/webapp/static;
        }

--重启uwsgi和nginx

#  kill -9 `ps -ef|egrep "uwsgi3|nginx" |grep -v grep |awk '{print $2}'` 

#  nohup uwsgi3 --ini webapp-up.ini &   --启动uwsgi3
#  /usr/local/nginx/sbin/nginx           --启动nginx

 netstat -anlp|egrep "80|81"
tcp  0  0   0.0.0.0:80     0.0.0.0:*    LISTEN    15767/nginx: master 
tcp  0  0   0.0.0.0:81     0.0.0.0:*    LISTEN    15756/uwsgi3

--访问http:// 172.18.108.136/admin 能看到以下内容,代表已经搭建成功
Docker手动构建 nginx+py3+uwsgi环境

可以看到这次访问已经有css样式了,比之前美观

--使用前面创建的帐号/密码登陆进去:admin/admin123
Docker手动构建 nginx+py3+uwsgi环境

--至此搭建完成