1、Linux基础优化

#!/bin/bash


#关闭防火墙和selinux
seli=`getenforce`
[ $seli="Enforcing" ] && setenforce 0 &> /dev/null
if `cat /etc/selinux/config  | grep SELINUX=disabled &>/dev/null`; then
        echo selinux已关闭
else
        sed -ri '/^SELINUX=/s#enforcing#disabled#p' /etc/selinux/config
fi
if `systemctl status firewalld.service &>/dev/null`;then
        systemctl stop firewalld.service
        systemctl disable firewalld.service
else
        echo firewall已关闭
fi

#替换为阿里源
version=$(echo `sed -nr 's/^.* ([0-9]+)\..*/\1/p' /etc/redhat-release`)
if [ $version -eq 7  ]; then
	rm -f /etc/yum.repos.d/* > /dev/null
cat << wcc > /etc/yum.repos.d/wcc.repo
[base]
name=CentOS-\$releasever - Base
baseurl=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/
enable=1
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/RPM-GPG-KEY-CentOS-\$releasever
[epel]
name=epel
baseurl=https://mirrors.aliyun.com/epel/\$releasever/x86_64/
enable=1
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-\$releasever

wcc
else
	echo "不是7版本"
fi


#更改网卡名
    #判断网卡名是否已经是eth
`ip a | grep "eth0"  > /dev/null` && { echo 网卡名已经更改,请输入no; }
    #判断版本是否等于7,后续写别的
if [ $version -ge 7 ]; then
            if `cat /etc/default/grub  | grep ifnames=0 > /dev/null` ; then
                    echo 配置文件已存在;
                    read -p "是否重新加载配置:yes or no ?" yorn
                    if [[ $yorn =~ [yY]([Ee][Ss])?  ]] ; then
                            grub2-mkconfig -o /etc/grub2.cfg
                    reboot
            fi
                    unset yorn 
            else
                    sed -ri '/CMDLINE/s#^(.*)"#\1 net.ifnames=0 "#' /etc/default/grub
                    grub2-mkconfig -o /etc/grub2.cfg
                    read -p "是否重启:yes or no ?" yorn
                    if [[ $yorn =~ [yY]([Ee][Ss])?  ]] ; then
                            reboot
                    fi
                    unset yorn 
            fi
fi


#更改vim
cat << vimr > /root/.vimrc
set ignorecase
set cursorline
set autoindent
autocmd BufNewFile *.sh exec ":call SetTitle()"
func SetTitle()
if expand("%:e") == 'sh'
call setline(1,"#!/bin/bash") 
call setline(2,"#") 
call setline(3,"#********************************************************************") 
call setline(4,"#Author:                liuwei") 
call setline(5,"#QQ:                    1461918614") 
call setline(6,"#Date:                  ".strftime("%Y-%m-%d"))
call setline(7,"#FileName:             ".expand("%"))
call setline(8,"#Description:          The test script") 
call setline(9,"#Copyright (C):         ".strftime("%Y")." All rights reserved")
call setline(10,"#********************************************************************") 
call setline(11,"") 
endif
endfunc
autocmd BufNewFile * normal G
vimr


#更改ssh端口
sed -i 's$^#Port .*$Port 2379$g' /etc/ssh/sshd_config
systemctl restart sshd


#内核参数优化
#ip_forward=`sysctl -a 2> sysctl.err | grep -w "net.ipv4.ip_forward"`
#conntrack_max=`sysctl -a 2> sysctl.err | grep -w "net.netfilter.nf_conntrack_max"`
#default_disable_ipv6=`sysctl -a 2> sysctl.err | grep -w "net.ipv6.conf.default.disable_ipv6"`
#all_disable_ipv6=`sysctl -a 2> sysctl.err | grep -w "net.ipv6.conf.all.disable_ipv6"`
#after_idle=`sysctl -a 2> sysctl.err | grep -w "net.ipv4.tcp_slow_start_after_idle"`
#pid_max=`sysctl -a 2> sysctl.err | grep -w "kernel.pid_max"`
#nonlocal_bind=`sysctl -a 2> sysctl.err | grep -w "net.ipv4.ip_nonlocal_bind"`
#somaxconn=`sysctl -a 2> sysctl.err | grep -w "net.core.somaxconn"`
#backlog=`sysctl -a 2> sysctl.err | grep -w "net.ipv4.tcp_max_syn_backlog"`

#打开最大文件符描述

#磁盘检测

#网络检测

2、编译安装Nginx

2.1 编译安装Nginx

[root@centos7 ~]# cd /usr/local/src/
[root@centos7 src]# useradd -s /sbin/nologin nginx
[root@centos7 src]# yum install gcc pcre-devel openssl-devel zlib-devel make wget -y
[root@centos7 src]# wget http://nginx.org/download/nginx-1.21.3.tar.gz
[root@centos7 src]# tar xf nginx-1.21.3.tar.gz 
[root@centos7 src]# cd nginx-1.21.3/
[root@centos7 nginx-1.21.3]# ./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
[root@centos7 nginx-1.21.3]# make && make install
[root@centos7 nginx-1.21.3]# chown -R nginx:nginx /apps/nginx


[root@centos7 nginx-1.21.3]# ll /apps/nginx/
total 0
drwxr-xr-x 2 nginx nginx 333 Sep 26 18:01 conf
drwxr-xr-x 2 nginx nginx  40 Sep 26 18:01 html
drwxr-xr-x 2 nginx nginx   6 Sep 26 18:01 logs
drwxr-xr-x 2 nginx nginx  19 Sep 26 18:01 sbin

conf:保存nginx所有的配置文件
html:目录中保存了nginx服务器的web文件
logs:用来保存nginx服务器的访问日志错误日志等日志
sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能

2.2 验证版本及编译参数

[root@centos7 nginx-1.21.3]# ls /apps/nginx/sbin/
nginx
[root@centos7 nginx-1.21.3]# ln -s /apps/nginx/sbin/nginx /usr/sbin/

#查看版本
[root@centos7 nginx-1.21.3]# nginx -v
nginx version: nginx/1.21.3

#查看编译参数
[root@centos7 nginx-1.21.3]# nginx -V
nginx version: nginx/1.21.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

2.3 启动和停止nginx测试访问web界面

#启动nginx
[root@centos7 nginx-1.21.3]# nginx

[root@centos7 nginx-1.21.3]# ss -lntp|grep nginx
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=7806,fd=6),("nginx",pid=7805,fd=6))

#关闭nginx
[root@centos7 nginx-1.21.3]# nginx -s stop
[root@centos7 nginx-1.21.3]# ss -lnt
State       Recv-Q Send-Q               Local Address:Port                              Peer Address:Port              
LISTEN      0      128                              *:22                                           *:*                  
LISTEN      0      100                      127.0.0.1:25                                           *:*                  
LISTEN      0      128                           [::]:22                                        [::]:*                  
LISTEN      0      100                          [::1]:25                                        [::]:* 

image.png

2.4 创建Nginx自启动文件

[root@centos7 nginx-1.21.3]# cat /usr/lib/systemd/system/nginx.service 
[Unit]
Desciption=nginx - high performance web server
Documentation=http://nginx.org/en/docs
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/apps/nginx/run/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP 
ExecStop=/bin/kill -s HUP 

[Install]
WantedBy=multi-user.target

#创建目录
[root@centos7 nginx-1.21.3]# mkdir /apps/nginx/run

#修改配置文件
[root@centos7 nginx-1.21.3]# vim /apps/nginx/conf/nginx.conf
pid /apps/nginx/run/nginx.pid;

2.5 验证Nginx自启动文件

[root@centos7 nginx-1.21.3]# systemctl daemon-reload
[root@centos7 nginx-1.21.3]# systemctl enable --now nginx
[root@centos7 nginx-1.21.3]# ll /apps/nginx/run/
total 4
-rw-r--r-- 1 root root 5 Sep 26 18:23 nginx.pid
[root@centos7 nginx-1.21.3]# ss -lntp|grep nginx
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=7934,fd=6),("nginx",pid=7933,fd=6))

2.6 给个nginx配置文件

user  nginx;
worker_processes  auto;
worker_cpu_affinity auto;

pid   /apps/nginx/run/nginx.pid;

events {
        worker_connections 10240;
	use epoll;
	accept_mutex on;
}

http {
        include /apps/nginx/conf.d/*.conf;
        include mime.types;
        default_type application/octet-stream;
	
	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      	  '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
        
	log_format access_json '{"@timestamp":"$time_iso8601",'
        '"host":"$server_addr",'
        '"clientip":"$remote_addr",'
        '"size":$body_bytes_sent,'
        '"responsetime":$request_time,'
        '"upstreamtime":"$upstream_response_time",'
        '"upstreamhost":"$upstream_addr",'
        '"http_host":"$host",'
        '"uri":"$uri",'
        '"user_port":"$remote_port",'
        '"method":"$request_method",'
        '"xff":"$http_x_forwarded_for",'
        '"referer":"$http_referer",'
        '"tcp_xff":"$proxy_protocol_addr",'
        '"http_user_agent":"$http_user_agent",'
        '"status":"$status"}';

        #gzip on;
        #gzip_comp_level 3;
        #gzip_min_length 64;
        #gzip_vary on;
        #gzip_types text/xml text/css  application/javascript;

	sendfile    on;
        keepalive_timeout  65;
        server {
                listen  80;
                server_name   www.wcc.cn;
                location / {
                        root /data/nginx;
                        index index.php index.html index.htm;
                }
                error_page   500 502 503 504 /50x.html;
                location = /50x.html {
                        root html;
                }
                location ~ \.php$ {
                        root           /data/nginx;
                        fastcgi_pass   127.0.0.1:9000;
                        fastcgi_index  index.php;
                        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
                        include        fastcgi_params;
                }
                location ~ ^/(ping|pm_status)$ {
                        include fastcgi_params;
                        fastcgi_pass 127.0.0.1:9000;
                        fastcgi_param PATH_TRANSLATED  $document_root$fastcgi_script_name;
                }
        }
}

3、编译安装php

3.1 编译安装php

[root@centos7 ~]# cd /usr/local/src/
[root@centos7 src]# yum install gcc openssl-devel libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel
[root@centos7 src]# wget http://php.net/distributions/php-7.4.23.tar.gz
[root@centos7 src]# tar xf php-7.4.23.tar.gz
[root@centos7 src]# cd php-7.4.23/

[root@centos7 php-7.4.23]# ./configure --prefix=/apps/php74 --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-openssl --with-zlib --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --enable-mbstring --enable-xml --enable-sockets --enable-fpm --enable-maintainer-zts --disable-fileinfo
[root@centos7 php-7.4.23]# make && make install

3.2 准备php配置文件

#生成配置文件
[root@centos7 php-7.4.23]# cp /usr/local/src/php-7.4.23/php.ini-production /etc/php.ini
[root@centos7 php-7.4.23]# cp sapi/fpm/php-fpm.service /usr/lib/systemd/system/
[root@centos7 php74]# cd /apps/php74/etc/
[root@centos7 etc]# cp php-fpm.conf.default php-fpm.conf
[root@centos7 etc]# cd php-fpm.d/
[root@centos7 php-fpm.d]# cp www.conf.default www.conf

[root@centos7 php-fpm.d]# vim www.conf
[root@centos7 php-fpm.d]# grep '^[^;]' www.conf
[www]
user = nginx
group = nginx
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.status_path = /pm_status
ping.path = /ping
access.log = log/$pool.access.log
slowlog = log/$pool.log.slow

#创建访问日志文件路径
[root@centos7 php-fpm.d]# mkdir /apps/php74/log

3.3 启动并验证php-fpm服务

[root@centos7 php-fpm.d]# /apps/php74/sbin/php-fpm -t
[27-Sep-2021 10:21:37] NOTICE: configuration file /apps/php74/etc/php-fpm.conf test is successful

[root@centos7 php-fpm.d]# ss -lntp|grep php
LISTEN     0      128    127.0.0.1:9000                     *:*                   users:(("php-fpm",pid=116651,fd=8),("php-fpm",pid=116650,fd=8),("php-fpm",pid=116649,fd=6))

4、安装mysql

4.1 源码安装

#先卸载mariadb安装包
[root@centos7 ~]# rpm -e --nodeps mariadb-libs

#安装所需要的依赖包
[root@centos7 ~]# yum -y install gcc gcc-c++ ncurses ncurses-devel cmake bison bison-devel

#下载安装包
[root@centos7 ~]# wget https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.34.tar.gz
[root@centos7 src]# wget http://downloads.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.gz

#授权相关目录
[root@centos7 src]# useradd -M -s /sbin/nologin mysql
[root@centos7 src]# mkdir /usr/local/mysql
[root@centos7 src]# mkdir /mysql/data -p
[root@centos7 src]# chown -R mysql:mysql /usr/local/mysql
[root@centos7 src]# chown -R mysql:mysql /mysql/data
[root@centos7 src]# chmod 750 /mysql/data

#解压安装
[root@centos7 src]# tar xf mysql-5.7.34.tar.gz 
[root@centos7 src]# tar xzf boost_1_59_0.tar.gz
[root@centos7 src]# cd mysql-5.7.34/
[root@centos7 mysql-5.7.34]# cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/mysql/data -DWITH_BOOST=../boost_1_59_0 -DSYSCONFDIR=/etc -DENABLED_LOCAL_INFILE=1 -DENABLE_DTRACE=0 -DDEFAULT_CHARSET=utf8mb4 -DDEFAULT_COLLATION=utf8mb4_general_ci -DWITH_EMBEDDED_SERVER=1
[root@centos7 mysql-5.7.34]# make -j  $(grep processor /proc/cpuinfo | wc -l)
[root@centos7 mysql-5.7.34]# make install
[root@centos7 mysql-5.7.34]# echo -e '\n\nexport PATH=/usr/local/mysql/bin:$PATH\n' >> /etc/profile && source /etc/profile
[root@centos7 mysql-5.7.34]# cp /usr/local/mysql/support-files/mysql.server   /etc/init.d/mysqld
[root@centos7 mysql-5.7.34]# chkconfig --add mysqld
[root@centos7 mysql-5.7.34]# chmod +x /etc/init.d/mysqld

4.2 配置文件

[root@centos7 src]# vim /etc/my.cnf

[client]
default-character-set=utf8mb4


[mysql]
default-character-set=utf8mb4

[mysqld]
################ basic settings ################
bind-address = 0.0.0.0
#
## MySQL 的 pid 号存放文件,这个文件不要建立,MySQL会自己建立
pid-file = /tmp/mysql.pid
## MysqlServer 的进程用户,这个用户需要自己建立
user = mysql

character_set_server = utf8mb4
collation-server = utf8mb4_unicode_ci
#
## 如果是 OFF 或(0),mysqld 在检查客户端连接时解析主机名。
## 如果是 ON 或(1),mysqld只使用 IP;
skip_name_resolve = 1
#
max_allowed_packet = 16777216
#
## 允许的最大同时客户端连接数。默认情况下,这是151
max_connections = 2000
#
## 运行错误连接后尝试的次数,默认 100
max_connect_errors = 1000
explicit_defaults_for_timestamp = 1
join_buffer_size = 134217728
#
## 交互式客户端连接后,没有任何操作的情况下,继续保持连接状态的秒数
interactive_timeout = 1800
#
## 服务器在关闭之前等待非交互式连接上的活动的秒数。
wait_timeout = 1800
read_buffer_size = 16777216
read_rnd_buffer_size = 33554432
sort_buffer_size = 33554432
key_buffer_size = 256M
transaction_isolation = READ-COMMITTED
#
############# log settings ############
log_error=/tmp/mysqld.log
expire_logs_days = 30
slow_query_log = 1
long_query_time = 2
#
## 在写入慢查询日志的语句中包含慢速管理语句
log_slow_admin_statements = 1
#
## 检查少于此行数的查询结果不会记录到慢查询日志中。
[client]
default-character-set=utf8mb4


[mysql]
default-character-set=utf8mb4

[mysqld]
################ basic settings ################
bind-address = 0.0.0.0
#
## MySQL 的 pid 号存放文件,这个文件不要建立,MySQL会自己建立
pid-file = /tmp/mysql.pid
## MysqlServer 的进程用户,这个用户需要自己建立
user = mysql

character_set_server = utf8mb4
collation-server = utf8mb4_unicode_ci
#
## 如果是 OFF 或(0),mysqld 在检查客户端连接时解析主机名。
## 如果是 ON 或(1),mysqld只使用 IP;
skip_name_resolve = 1
#
max_allowed_packet = 16777216
#
## 允许的最大同时客户端连接数。默认情况下,这是151
max_connections = 2000
#
## 运行错误连接后尝试的次数,默认 100
max_connect_errors = 1000
explicit_defaults_for_timestamp = 1
join_buffer_size = 134217728
#
## 交互式客户端连接后,没有任何操作的情况下,继续保持连接状态的秒数
interactive_timeout = 1800
#
## 服务器在关闭之前等待非交互式连接上的活动的秒数。
wait_timeout = 1800
read_buffer_size = 16777216
read_rnd_buffer_size = 33554432
sort_buffer_size = 33554432
key_buffer_size = 256M
transaction_isolation = READ-COMMITTED
#
############# log settings ############
log_error=/tmp/mysqld.log
expire_logs_days = 30
slow_query_log = 1
long_query_time = 2
#
## 在写入慢查询日志的语句中包含慢速管理语句
log_slow_admin_statements = 1
#
## 检查少于此行数的查询结果不会记录到慢查询日志中。
min_examined_row_limit = 100
#
############ innodb settings ##########
innodb_buffer_pool_size = 1G
innodb_sort_buffer_size = 27108864
innodb_buffer_pool_load_at_startup = 1
innodb_buffer_pool_dump_at_shutdown = 1
innodb_lock_wait_timeout = 5
innodb_flush_method = O_DIRECT
innodb_file_format = Barracuda
innodb_file_format_max = Barracuda
innodb_thread_concurrency = 8
innodb_flush_neighbors = 1
innodb_purge_threads = 4
innodb_large_prefix = 1
innodb_print_all_deadlocks = 1
innodb_strict_mode = 1
innodb_file_per_table = ON
innodb_log_file_size = 500M
innodb_log_buffer_size = 20M
innodb_log_files_in_group = 3
innodb_flush_log_at_trx_commit=1

4.3 初始化重启服务

[root@centos7 src]# mysqld   --initialize   --user=mysql
[root@centos7 src]# systemctl  start  mysql
[root@centos7 src]# ss -lntp |grep mysql