[实验] Nginx + Keepalived 网站服务负载均衡加高可用的实现

纪念:站主于 2021 年 2 月完成了此开源实验,并将过程中的所有命令经过整理和注释以后,形成以下教程

步骤一:拓扑图

1.1 服务器列表

client enp1s0: 172.16.1.99

proxy1 enp1s0: 172.16.0.101
enp7s0: 172.16.1.101
virtual IP: 172.16.1.100

proxy2 enp1s0: 172.16.0.102
enp7s0: 172.16.1.102

web1 enp1s0: 172.16.0.11

web2 enp1s0: 172.16.0.12

1.2 拓扑图

                      proxy1                                       web1
                      enp7s0:172.16.1.101 enp1s0:172.16.0.101      enp1s0:172.16.0.11
                      virtual IP:172.16.1.100
client
enp1s0:172.16.1.99
                      proxy2                                       web2
                      enp7s0:172.16.1.102 enp1s0:172.16.0.102      enp1s0:172.16.0.12

1.3 拓扑图简介

1) web1 安装 Nginx,web2 安装 Apache 实现网站服务
2) proxy1 和 proxy2 安装 Nginx 实现网站代理,轮询代理 web1、web2 上的网站服务实现负载均衡
3) 虚拟 IP 172.16.1.90 通过 Keepalived 默认放在 proxy1 的 enp7s0 网卡上,如果 proxy1 宕机或者检测到自己 Nginx 代理进程死掉,则虚拟 IP 172.16.1.90 则挂在 proxy2 的 enp7s0 网卡上实现高可用
4) 如果 web1 和 web2 中有一台服务器宕机,则 proxy1 和 proxy2 会自动不再向这台服务器请求网站服务,直到它恢复正常
5) 最终达到的效果是 client 向虚拟 IP 请求网站服务,此时如果 proxy1 正常就代表虚拟 IP 轮询调度 web1 和 web2 上的网站服务,再返回给 client。如果 proxy1 宕机则由 proxy2 代表虚拟 IP 完成次操作

步骤二: 系统环境要求

1) 所有服务器的系统都需要是 CentOS 8 版本
2) 所有服务器都要关闭防火墙
3) 所有服务器都要关闭 SELinux
4) 所有服务器系统都要配置好可用的软件源
5) 需要按照拓扑图给对应的服务器配置好 IP 地址和主机名
6) client 的 enp1s0 网卡、proxy1 的 enp7s0 网卡和 proxy2 的 enp7s0 网卡要可以相互 ping 通自己和对方的 IP
7) proxy1 的 enp1s0 网卡、proxy2 的 enp1s0 网卡、web1 的 enp1s0 网卡和 web2 的 enp1s0 网卡要可以相互 ping 通自己和对方的 IP 地址

步骤三:搭建网站服务

3.1 在 web1 上搭建网站服务

3.1.1 在 web1 上安装 Nginx

(只在 web1 上执行以下步骤)

# yum -y install nginx
3.1.2 给 web1 制定网页

(只在 web1 上执行以下步骤)

# echo web1 > /usr/share/nginx/html/index.html
3.1.3 启动 Nginx 并将它设置为开机自启

(只在 web1 上执行以下步骤)

# systemctl enable --now nginx

3.2 在 web2 上搭建网站服务

3.2.1 在 web2 上安装 Apache

(只在 web2 上执行以下步骤)

# yum -y install httpd
3.2.2 给 web2 制定网页

(只在 web2 上执行以下步骤)

# echo web2 > /var/www/html/index.html
3.2.3 启动 Apache 并将它设置为开机自启

(只在 web2 上执行以下步骤)

# systemctl enable --now httpd

步骤四:搭建代理服务

4.1 安装 Nginx

(分别在 proxy1 和 proxy2 上执行以下步骤)

# yum -y install nginx

4.2 修改 Nginx 配置文件

(分别在 proxy1 和 proxy2 上执行以下步骤)

# vi /etc/nginx/nginx.conf

将部分内容修改如下:

......
http {
    upstream webserver {
        server 172.16.0.11:80;
        server 172.16.0.12:80;
    }
......
    server {
        listen       80;

        location / {
        proxy_pass http://webserver;
        }
    }
......
}

4.3 启动 Nginx 并将它设置为开机自启

(分别在 proxy1 和 proxy2 上执行以下步骤)

# systemctl enable --now nginx

步骤五:搭建高可用服务

5.1 安装 Keepalived

(分别在 proxy1 和 proxy2 上执行以下步骤)

# yum -y install keepalived

5.2 创建 Keepalived 检查脚本

5.2.1 创建 Keepalived 检查脚本

(分别在 proxy1 和 proxy2 上执行以下步骤)

# vi /etc/keepalived/nginx_check.sh

创建以下内容:

#!/bin/bash

if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
    systemctl stop nginx
    sleep 5
    if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
        killall keepalived
    fi
fi

(补充:这里以检测 Nginx 没启动就启动 Nginx,5 秒后 Nginx 要是还没有启动就关闭 keepalived 为例)

5.2.2 给 Keepalived 检查脚本执行权限

(分别在 proxy1 和 proxy2 上执行以下步骤)

# chmod u+x /etc/keepalived/nginx_check.sh

5.3 修改 proxy1 上的 Keepalived 配置文件

(只在 proxy1 上执行以下步骤)

# vim /etc/keepalived/keepalived.conf

将全部内容修改如下:

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id proxy1
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight 20
}

vrrp_instance VI_1 {
    state MASTER
    interface enp7s0
    virtual_router_id 90
    priority 101
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
    chk_nginx
    }
    virtual_ipaddress {
        172.16.1.100
    }
}


补充:
1) script “/etc/keepalived/nginx_check.sh” 代表使用的检测脚本是 /etc/keepalived/nginx_check.sh
2) interface enp7s0 代表虚拟 IP 将挂载在 enp7s0 网卡上
3) priority 代表修建级是 101,数字越大优先级越高
4) 172.16.1.100 代表虚拟 IP 是 172.16.1.100

5.4 修改 proxy2 上的 Keepalived 配置文件

(只在 proxy2 上执行以下步骤)

# vim /etc/keepalived/keepalived.conf

将全部内容修改如下:

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id proxy1
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_script chk_nginx {
     script "/etc/keepalived/nginx_check.sh"
     interval 2
     weight 20
}

vrrp_instance VI_1 {
    state BACKUP
    interface enp7s0
    virtual_router_id 90
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
    chk_nginx
    }
    virtual_ipaddress {
        172.16.1.100
    }
}


补充:
1) script “/etc/keepalived/nginx_check.sh” 代表使用的检测脚本是 /etc/keepalived/nginx_check.sh
2) interface enp7s0 代表虚拟 IP 将挂载在 enp7s0 网卡上
3) priority 代表修建级是 99,数字越大优先级越高
4) 172.16.1.100 代表虚拟 IP 是 172.16.1.100

5.5 启动 Keepalived 并将它设置为开机自启

(分别在 proxy1 和 proxy2 上执行以下步骤)

# systemctl enable --now keepalived.service

步骤六:测试网站负载均衡加高可用

6.1 正常情况下测试网站服务

(只在 client 上执行以下步骤)

# curl 172.16.1.100

(补充:重复以上命令会发现重复显示 web1 和 web2)

6.2 在单节点故障的情况下测试网站服务

6.2.1 关闭 proxy1、proxy2、web1、web2 中的任意一台服务器

(只在 proxy1、proxy2、web1、web2 中的任意一台服务器上执行以下步骤)

# poweroff
6.2.2 测试网站服务

(只在 client 上执行以下步骤)

# curl 172.16.1.100

(补充:重复以上命令会发现重复显示 web1 和 web2)

[内容] Nginx 的使用 (开启网页目录结构)

注意:

在开启 Nginx 网页目录结构之前要先安装 Nginx

正文:

内容一:开启 Nginx 目录结构的目的

默认安装了 Nginx 之后,被访问的网页只会显示一张 Nginx 的欢迎页面或者 404
有时候我们需要让网页现实网页根 “/” 目录中的文件和目录,用于提供 http 下载等功能,这个时候就需要开启 Nginx 的目录结构

内容二:开启 Nginx 目录结构的方法

# vi /usr/local/nginx/conf/nginx.conf

将部分内容修改如下:

http {
......
server {
......
location /{
......
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
charset utf-8,gbk,gb2312;
add_header Content-Disposition attachment;
......
}
......
}
......
}
......


补充:
1) 这里是在 localtion 下面添加开启目录结构的参数
2) 这里的 autoindex on 表示开启目录结构
3) 这里的 autoindex_exact_size on 表示显示文件大小
4) 这里的 autoindex_localtime on 表示显示服务器的时间
5) 这里的 charset utf-8,gbk,gb2312 表示避免中文乱码
6) 这里的 add_header Content-Disposition attachment 表示文件可下载

或者:

# vi /usr/local/nginx/conf/nginx.conf

将部分内容修改如下:

http {
......
server {
......
location /{
......
}
......
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
charset utf-8,gbk,gb2312;
add_header Content-Disposition attachment;
......
}
......
}
......


补充:
1) 这里是在 server 下面添加开启目录结构的参数
2) 这里的 autoindex on 表示开启目录结构
3) 这里的 autoindex_exact_size on 表示显示文件大小
4) 这里的 autoindex_localtime on 表示显示服务器的时间
5) 这里的 charset utf-8,gbk,gb2312 表示避免中文乱码
6) 这里的 add_header Content-Disposition attachment 表示文件可下载

或者:

# vi /usr/local/nginx/conf/nginx.conf

将部分内容修改如下:

http {
......
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
charset utf-8,gbk,gb2312;
add_header Content-Disposition attachment;
......
server {
......
location /{
......
}
......
}
......
}
......


补充:
1) 这里是在 http 下面添加开启目录结构的参数
2) 这里的 autoindex on 表示开启目录结构
3) 这里的 autoindex_exact_size on 表示显示文件大小
4) 这里的 autoindex_localtime on 表示显示服务器的时间
5) 这里的 charset utf-8,gbk,gb2312 表示避免中文乱码
6) 这里的 add_header Content-Disposition attachment 表示文件可下载

[工具] Shell 自动化部署 LNMP + SSL 平台 (CentOS Linux 8 版)

介绍

基本信息

作者:朱明宇
名称:自动化部署 LNMP + SSL 平台
作用:自动化安装 LNMP + SSL,即通过 Linux、Nginx、MariaDB、PHP、php-fpm、SSL,实现 HTTPS

使用方法

1. 将网站的网页数据备份、网站的 SSL 公钥、网站的 SSL 私钥、网站的数据库备份和本脚本,5 个文件放在同一目录下
2. 如果没有网站的数据库备份则将网页数据备份、网站的 SSL 公钥、网站的 SSL 私钥和本脚本,4 个文件放在同一目录下
3. 在此脚本的分割线内写入相应的内容
4. 服务器都要开启 SELinux
5. 给此脚本添加执行权限
6. 执行此脚本:./<此脚本>

脚本分割线里的变量

1. webdomain=”eternalcenter.com” #网站的域名,注意不要在前面加任何前缀
2. webtar=”eternalcenter-backup-*.tar.gz”网站的网页数据备份,如果没有这个备份,可以下载一个开源的 WordPress 网页程序
3. webcrt=”eternalcenter.com.crt” #网站 SSL 的公钥,可以自己创建也可以在 FreeSSL 上申请
4. webkey=”eternalcenter.com.key” #网站 SSL 的私钥,可以自己创建也可以在 FreeSSL 上申请
5. sqlbackup=”eternalcenter-backup-*.sql” #网站数据库数据备份,如果没有这个备份(数据库是全量备份),则这里可以为空
6. db=”ec” #网站在数据库中库
7. dbuser=”ec” #网站在数据库中的用户
8. dbuserpw=”eternalcenter” #网站在数据库中的用户密码
9. dbrootpw=”eternalcenter” #数据库的 root 密码

注意

1. 服务器的系统需要是 CentOS 8 版本
2. 服务器系统要配置好可用的软件源
3. 服务器要能够连接外网

脚本

#!/bin/bash

####################### Separator ########################
webdomain="eternalcenter.com"
webtar="eternalcenter-backup-*.tar.gz"
webcrt="eternalcenter.com.crt"
webkey="eternalcenter.com.key"
sqlbackup="eternalcenter-backup-*.sql"
db="ec"
dbuser="ec"
dbuserpw="eternalcenter"
dbrootpw="eternalcenter"
####################### Separator ########################

#Determine whether SELinux is on
getenforce | grep Enforcing
if [ $? -ne 0 ];then
	echo "SELinux is not set to enforcing mode and cannot continue"
	exit 2
fi

#Determine whether the required file exists
ls $webtar
if [ $? -ne 0 ];then
	echo "No web page data backup, unable to continue"
	exit 2
fi

ls $webcrt
if [ $? -ne 0 ];then
	echo "Cannot continue without site public key"
	exit 2
fi

ls $webkey
if [ $? -ne 0 ];then
	echo "Unable to continue without site private key"
	exit 2
fi

#Update system
yum clean all
yum repolist
yum makecache
yum -y update

#Make sure the required software is installed
yum -y install tar
yum -y install firewalld

#Deploying Nginx
yum -y install nginx

echo 'worker_processes  1;

events {
    worker_connections  1024;
}

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  60;
    client_body_timeout 20s;
    client_header_timeout 10s;
    send_timeout 30s;

    server {
        listen       80;
        limit_req zone=one burst=5;
        server_name www.eternalcenter.com eternalcenter.com;

        rewrite ^/(.*)$ https://eternalcenter.com/$1 permanent;
      
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        }

    server {
        listen       443 ssl;
        server_name www.eternalcenter.com eternalcenter.com;

        if ($request_method !~ ^(GET|POST)$){
        return 444;
        }

        ssl_certificate      /etc/nginx/ssl/eternalcenter.com.crt;
        ssl_certificate_key  /etc/nginx/ssl/eternalcenter.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location ~ \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
            fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/$fastcgi_script_name;
            include fastcgi_params;
        } 

        location / {
        root html;
        index index.php index.html index.htm;

        if (-f $request_filename/index.html){rewrite (.) $1/index.html break;}
        if (-f $request_filename/index.php){rewrite (.) $1/index.php;}
        if (!-f $request_filename){rewrite (.) /index.php;}
        
        }

        location ~ ^/\.user\.ini {
        deny all;
        }
    
        location ~*\.(jpd|jpeg|gif|png|css|js|ico|xml)$ {
        expires 30d;
        }

        error_page  404              /404.html;

        }

        gzip on;
	gzip_min_length 1000;
	gzip_comp_level 4;
	gzip_types text/plain test/css application/json application/x-javascript text/xml application/xml
	application/xml+rss text/javascripts;

	client_header_buffer_size 1k;
	large_client_header_buffers 4 4k;

	open_file_cache max=2000 inactive=20s;
	open_file_cache_valid  60s;
	open_file_cache_min_uses 5;
	open_file_cache_errors off;

}' > /etc/nginx/nginx.conf

sed -i "s/server_name www.eternalcenter.com eternalcenter.com;/server_name www.$webdomain $webdomain;/" /etc/nginx/nginx.conf
sed -i "s@rewrite ^/(.*)$ https://eternalcenter.com/\$1 permanent@rewrite ^/(.*)$ https://$webdomain/\$1 permanent@" /etc/nginx/nginx.conf;
sed -i "s/eternalcenter.com.crt/$webcrt/" /etc/nginx/nginx.conf
sed -i "s/eternalcenter.com.key/$webkey/" /etc/nginx/nginx.conf

mkdir /etc/nginx/ssl
mv $webcrt /etc/nginx/ssl
mv $webkey /etc/nginx/ssl
chcon -t httpd_config_t /etc/nginx/ssl/$webcrt
chcon -t httpd_config_t /etc/nginx/ssl/$webkey
chcon -t httpd_config_t /etc/nginx/ssl/

rm -rf /usr/share/nginx/html/*
tar -xvf $webtar -C /usr/share/nginx/html/ && rm -rf $webtar
chcon -t httpd_sys_content_t -R /usr/share/nginx/html/*

yum -y install sendmail
yum -y install policycoreutils
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1
setsebool -P httpd_can_sendmail 1
setsebool -P httpd_can_connect_ftp 1
setsebool -P httpd_unified 1
setsebool -P httpd_enable_cgi 1
setsebool -P httpd_builtin_scripting 1
setsebool -P mysql_connect_http 1

systemctl start nginx
systemctl enable nginx

#Deploy MariaDB
yum -y install mariadb mariadb-server

grep "^log_bin=" /etc/my.cnf.d/mariadb-server.cnf
if [ $? -ne 0 ];then
	sed -i '/^datadir/a log_bin=ec' /etc/my.cnf.d/mariadb-server.cnf
fi

grep "^binlog_format=" /etc/my.cnf.d/mariadb-server.cnf
if [ $? -ne 0 ];then
	sed -i '/^datadir/a binlog_format=\"mixed\"' /etc/my.cnf.d/mariadb-server.cnf
fi

grep "^server_id=" /etc/my.cnf.d/mariadb-server.cnf
if [ $? -ne 0 ];then
	sed -i '/^datadir/a server_id=51' /etc/my.cnf.d/mariadb-server.cnf
fi

sed -i 's/^plugin-load-add=auth_gssapi.so/#plugin-load-add=auth_gssapi.so/' /etc/my.cnf.d/auth_gssapi.cnf

sed -i '/^user=.*/d' /etc/my.cnf.d/mariadb-server.cnf
sed -i "/\[mysqld\]/a user=mysql" /etc/my.cnf.d/mariadb-server.cnf

sed -i '/^bind-address=.*/d' /etc/my.cnf.d/mariadb-server.cnf
sed -i "/\[mysqld\]/a bind-address=127.0.0.1" /etc/my.cnf.d/mariadb-server.cnf

chown -R mysql /var/lib/mysql

systemctl start mariadb
systemctl enable mariadb

ls $sqlbackup
if [ $? -ne 0 ];then
        mysql -uroot -e "create database $db;"
        mysql -uroot -e "create user \"$dbuser\"@\"localhost\" identified by \"$dbuserpw\";"
        mysql -uroot -e "grant all privileges on $db.* to \"$dbuser\"@\"localhost\" identified by \"$dbuserpw\";"
        mysql -uroot -e "set password for 'root'@'localhost'=password(\"$dbrootpw\")"
else
        mysql -uroot -e "create database $db;"
        mysql -uroot $db < $sqlbackup
	mysql -uroot -e "create user \"$dbuser\"@\"localhost\" identified by \"$dbuserpw\";"
	mysql -uroot -e "grant all privileges on $db.* to \"$dbuser\"@\"localhost\" identified by \"$dbuserpw\";"
	mysql -uroot -e "set password for 'root'@'localhost'=password(\"$dbrootpw\")"
	rm -rf $sqlbackup
fi
	
systemctl restart mariadb

#Deploy PHP
yum -y install php php-fpm php-mysqlnd php-gd php-mbstring php-opcache php-json php-xml php-xmlrpc php-pecl-zip
useradd php-fpm -s /sbin/nologin
chown -R php-fpm:php-fpm /usr/share/nginx/html

sed -i /"^user =.*"/d /etc/php-fpm.conf
sed -i /"^group =.*"/d /etc/php-fpm.conf
sed -i /"^listen =.*"/d /etc/php-fpm.conf
sed -i /"^[www]"/d /etc/php-fpm.conf
sed -i /"^pm = .*"/d /etc/php-fpm.conf
sed -i /"^pm.start_servers = .*"/d /etc/php-fpm.conf
sed -i /"^pm.min_spare_servers = .*"/d /etc/php-fpm.conf
sed -i /"^pm.max_spare_servers = .*"/d /etc/php-fpm.conf
sed -i /"^pm.max_children = .*"/d /etc/php-fpm.conf
sed -i /"^pm.max_requests = .*"/d /etc/php-fpm.conf
sed -i /"^request_terminate_timeout = .*"/d /etc/php-fpm.conf

echo '[www]' >> /etc/php-fpm.conf
echo 'user = php-fpm' >> /etc/php-fpm.conf
echo 'group = php-fpm' >> /etc/php-fpm.conf
echo 'listen = 127.0.0.1:9000' >> /etc/php-fpm.conf
echo 'pm = dynamic' >> /etc/php-fpm.conf
echo 'pm.start_servers = 2' >> /etc/php-fpm.conf
echo 'pm.min_spare_servers = 2' >> /etc/php-fpm.conf
echo 'pm.max_spare_servers = 4' >> /etc/php-fpm.conf
echo 'pm.max_children = 4' >> /etc/php-fpm.conf
echo 'pm.max_requests = 1024' >> /etc/php-fpm.conf
echo 'request_terminate_timeout = 300' >> /etc/php-fpm.conf

systemctl start php-fpm
systemctl enable php-fpm

#Improve system performance
grep "^* soft nofile" /etc/security/limits.conf
if [ $? -ne 0 ];then
	echo '* soft nofile 1024' >> /etc/security/limits.conf
fi

grep "^* hard nofile" /etc/security/limits.conf
if [ $? -ne 0 ];then
	echo '* hard nofile 1024' >> /etc/security/limits.conf
fi

#Open firewall
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --add-port=443/tcp --permanent
firewall-cmd --reload

#Limit log space
echo "/var/log/mariadb/mariadb.log {
        create 600 mysql mysql
        notifempty
	daily
        rotate 3
        missingok
        compress
    postrotate
	# just if mysqld is really running
        if [ -e /run/mariadb/mariadb.pid ]
        then
           kill -1 $(</run/mariadb/mariadb.pid)
        fi
    endscript
}" > /etc/logrotate.d/mariadb

echo "/var/log/nginx/*log {
    create 0664 nginx root
    size 1024M
    rotate 1
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}" > /etc/logrotate.d/nginx

echo "/var/log/php-fpm/*log {
    size 100M
    rotate 1
    missingok
    notifempty
    sharedscripts
    delaycompress
    postrotate
        /bin/kill -SIGUSR1 `cat /run/php-fpm/php-fpm.pid 2>/dev/null` 2>/dev/null || true
    endscript
}" > /etc/logrotate.d/php-fpm

echo "/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
    size 100M
    rotate 1
    missingok
    sharedscripts
    postrotate
        /usr/bin/systemctl kill -s HUP rsyslog.service >/dev/null 2>&1 || true
    endscript
}" > /etc/logrotate.d/syslog

#Delete this script
scriptwhere=`readlink -f "$0"`
rm -rf $scriptwhere

#Restart the system
reboot

[实验] LNMP 平台的搭建 (openSUSE Leap 15 版)

步骤一:LNMP 简介

LNMP 是一个实现网站服务的方法,它由 4 样东西组成:
1) Linux 系统
2) Nginx 网页服务
3) MariaDB 数据库
4) PHP 网页程序

步骤二:系统环境要求

1) 服务器的系统需要是 openSUSE 15 版本
2) 服务器要关闭防火墙
3) 服务器系统要配置好可用的软件源(最好是软件数量最多的官方版本)

步骤三:搭建 LNMP

3.1 Nginx 网页服务

3.1.1 安装 Nginx 网页服务
# zypper -n install nginx
3.1.2 配置 Nginx 网页服务的配置文件
3.1.2.1 删除原有的 Nginx 服务的配置文件
# rm /etc/nginx/nginx.conf
3.1.2.2 创建新的 Nginx 网页服务的配置文件
# cp /etc/nginx/nginx.conf.default /etc/nginx.conf
3.1.2.3 配置 Nginx 网页服务的配置文件
# vi /etc/nginx/nginx.conf

将其中的:

......
        location / {
            root   html;
            index  index.html index.htm;
        }
......
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
......

修改为:

......
        location / {
            root   html;
            index  index.php index.html index.htm;
        }
......
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
        #   fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi.conf;
        }
......

(补充:这里以让 Nginx 将对于 PHP 的请求传递到本机的 9000 端口为例)

3.1.3 启动 Nginx 网页服务
# systemctl start nginx

3.2 MariaDB 数据库

3.2.1 安装 MariaDB 数据库
# zypper -n install mariadb mariadb-server
3.2.2 启动 MariaDB 数据库
# systemctl start mariadb

3.3 PHP 环境和连接服务

3.3.1 安装 PHP 环境和连接服务
# zypper -n install php7 php7-fpm php7-mysql php7-gd php7-mbstring php7-opcache php7-json php7-xmlrpc php7-zlib
3.3.2 创建提供 PHP 连接服务的用户
# useradd php-fpm -s /sbin/nologin
3.3.3 配置 PHP 连接服务的配置文件
# vi /etc/php-fpm.conf

将以下内容:

......
user = nouser
group = nouser
......

修改为:

......
user = php-fpm
group = users
listen = 127.0.0.1:9000
......


补充:这里以
1) 以 php-fpm 用户和 users 用户组的身份启动 php-fpm
2) 让 php-fpm 监听本地 9000 端口为例

步骤四:后续工作

1) 给 MariaDB 数据库设置用于存储网页数据的用户和密码
2) 将 PHP 网页程序放到 Nginx 的网页目录下(/srv/www/htdocs)
3) 给 PHP 网页程序设置用于连接 MariaDB 数据库的用户和密码

步骤五:测试 LNMP 平台

使用浏览器访问服务器 IP 地址就可以看到对应 PHP 网页了

[实验] Django 服务的搭建

纪念:站主于 2020 年 3 月完成了此开源实验,并将过程中的所有命令经过整理和注释以后,形成以下教程

注意:

文中的 python 系统名和 mysite 项目只是站主在本次操作中随意取的名称,读者可以根据自己的喜好换成任意别的名称

正文:

步骤一:系统环境要求

1) 服务器的系统需要是 CentOS Linux 7 版本
2) 服务器要关闭防火墙
3) 服务器要关闭 SELinux
4) 服务器系统要配置好可用的软件源
5) 服务器要能够连接外网

步骤二:安装 Django

2.1 安装 Python3

[root@python ~]# yum -y install python3

2.2 创建并进入 Django 项目的目录

[root@python ~]# mkdir project
[root@python ~]# cd project

2.3 将 Django 项目的目录指定为 Django 环境

[root@python project]# python3 -m venv django_env

2.4 进入 Django 环境

[root@python project]# source django_env/bin/activate
(django_env) [root@python project]# pip install django==1.11.6
Collecting django==1.11.6
  Downloading https://files.pythonhosted.org/packages/82/33/f9d2871f3aed5062661711bf91b3ebb03daa52cc0e1c37925f3e0c4508c5/Django-1.11.6-py2.py3-none-any.whl (6.9MB)
    100% |████████████████████████████████| 7.0MB 12kB/s 
Collecting pytz (from django==1.11.6)
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)",)': /simple/pytz/
  Downloading https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl (509kB)
    100% |████████████████████████████████| 512kB 15kB/s 
Installing collected packages: pytz, django
Successfully installed django-1.11.6 pytz-2019.3
You are using pip version 9.0.3, however version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(django_env) [root@python project]# 


补充:
1) 这里以安装 1.11.6 版本的 django 为例
2) 如果向直接安装最新版本的 django 可以使用 pip install django 命令

2.5 检验 Django 环境是否成功

(django_env) [root@python project]# python
Python 3.6.8 (default, Aug  7 2019, 17:28:10) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__version__
'1.11.6'
>>> exit()

步骤三:创建 mysite 项目

3.1 创建 mysite 项目

(django_env) [root@python project]# django-admin startproject mysite

3.2 mysite 项目的目录

3.2.1 安装 tree 目录显示软件
# yum -y install tree
3.2.2 显示 mysite 项目的目录
(django_env) [root@python project]# cd mysite
(django_env) [root@python mysite]# tree
.
├── manage.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

1 directory, 5 files

3.3 Django 项目目录介绍

1) mysite 此 Django 项目的容器
2) manage.py 命令行工具,与 Django 项目进行交互
3) mysite/init.py 空文件,通知 Python 此项目是一个 Python 包
4) mysite/settings.py 此 Django 项目的配置文件
5) mysite/urls.py 此 Django 项目的 URL 声明和 Django 的网站“目录”
6) mysite/wsgi.py WSGI 兼容 Web 服务器的入口

步骤四:启动 Django 服务

4.1 启动 Django 服务

(django_env) [root@python mysite]# python manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
February 27, 2020 - 05:35:30
Django version 1.11.6, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

(补充:这里以使用 8000 端口开启网站服务为例)

4.2 测试 Django 服务

通过浏览器访问以下网址:

http://127.0.0.1:8000/admin