Рубрики
Uncategorized

Больше, чем создание серверной среды разработки SNMP

Автор оригинала: David Wong.

Предисловие

Эта цель состоит в том, чтобы установить ряд программных сервисов, обычно используемых в серверной разработке в системе CentOS 7.5, недавно установленной на виртуальной машине (установка CentOS здесь не представлена), и развернуть веб-сайт с php MyAdmin в качестве примера

  • Nginx(1.16)
  • MySQL (8.0, запуск)
  • PHP(7.3)
  • Редис(1.5)
  • memcached(1.4)
  • Композитор(1.8)
  • phpMyAdmin(4.8)
  • nodejs(10.15)
  • пряжа(1.15)

Важное примечание: если вы считаете, что устанавливать и настраивать один за другим слишком сложно, рекомендуется использовать инструмент визуального управления pagoda для работы. В принципе, операция в один клик может значительно повысить эффективность. Короче говоря, это круто! (конечно, это не идеально, например, когда версия инструмента не поддерживает установку MySQL 8.0 в Ubuntu)

Назначение

IP-адрес виртуальной машины является 192.168.8.15 , Имя пользователя администратора сорго , Имя пользователя для выполнения служебной программы www , Каталог ликвидации веб-сайтов /данные/wwwroot , Установка и настройка, если не указано иное корневые Действия пользователя, После выполнения команды “Изменить файл” в следующей строке начинается отступ на 4 пробела вправо в качестве содержимого этого редактирования

После выполнения команды “Изменить файл” в следующей строке начинается отступ на 4 пробела вправо в качестве содержимого этого редактирования

Установка виртуальной машины VMware может быть завершена менее чем за 20 минут (базовая версия веб-сервера 1810, выберите китайскую среду, исходный код yum по умолчанию равен 163. Com)

Настройки пользователя

useradd www -s /usr/sbin/nologin
useradd -G www sorgo
passwd sorgo
#Give the root permission to the sorgo user, and do not need to enter the password when switching the root, and view the existing permission ` - L '
visudo
    #Edit content:
    #Add one to indicate that sorgo can use 'sudo' to execute root permission
    sorgo ALL=(ALL) NOPASSWD: ALL

Глобальные параметры псевдонима команды

vim /etc/bashrc
    #Add content:
    alias s-start='systemctl start'
    alias s-stop='systemctl stop'
    alias s-restart='systemctl restart'
    alias s-enable='systemctl enable'
    alias s-disable='systemctl disablep'
    alias s-status='systemctl status'
    alias vi='vim'
    alias ll='ls -laph'
    alias ..='cd ..'
    alias nrd='npm run dev'
    alias nrh='npm run hot'
    alias nrp='npm run production'
    alias nrw='npm run watch'
    alias nrww='npm run watch-poll'
    alias yrd='yarn run dev'
    alias yrh='yarn run hot'
    alias yrp='yarn run production'
    alias yrw='yarn run watch'
    alias yrwp='yarn run watch-poll'
    alias pa='php artisan'
    alias phpspec='vendor/bin/phpspec'
    alias phpunit='vendor/bin/phpunit'
#Make changes effective immediately
source /etc/bashrc

Каталог веб-сайтов и разрешения

#Project directory
mkdir -p /data/wwwroot/
#Log directory
mkdir -p  /data/wwwlogs/nginx/
#Installation directory of basic application of website
mkdir /data/server/
Empower
chown -R sorgo:www /data/
chmod -Rf g+s /data/

Конфигурация сетевой карты

#Check the name of the network card. The column on the left is
ifconfig
#Edit the network card configuration to fix the IP of NAT mode
vi /etc/sysconfig/network-scripts/ifcfg-ens33
    #Edit content:
    #Key content of configuration file, for reference only
    NAME=ens33
    DEVICE=ens33
    DEFROUTE=yes
    ONBOOT=yes
    #Set to static with 'IPADDR'`
    BOOTPROTO=static
    IPADDR=192.168.8.15
    NETMASK=255.255.255.0
    
#Restart effective
systemctl restart network

Конфигурация источника Yum

Источник Али

cd /etc/yum.repos.d
mv CentOS-Base.repo CentOS-Base.repo.bak
wget -O CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum clean all
yum makecache

163 источника Официальное использование помощь

cd /etc/yum.repos.d/  
mv CentOS-Base.repo CentOS-Base.repo.backup  
wget -O CentOS-Base.repo https://mirrors.163.com/.help/CentOS7-Base-163.repo
yum clean all
yum makecache

#Update all the programs installed in the system, and choose to do so
yum update -y

Некоторые команды от yum

Yum list all
Yum list installed? Lists the installed
Yum list available? Lists those that are not installed
Yum remove software? Uninstall the software
Yum install software
Yum search keyword search for keyword related software
Yum whatprovides file search for packages containing this file
Yum reinstall software? Install the software from scratch
Yum localinstall third-party software - install the software and resolve dependencies
Query software information
List software groups from Yum groups list
Yum groups install
Yum groups remove - uninstall a group
Yum groups info? View group information
Yum repolist? View installed sources

Выключите брандмауэр

В CentOS 7.5 брандмауэр запускается по умолчанию. В среде разработки для удобства брандмауэр закрывается напрямую

#View status
systemctl status firewalld
#Cancel startup
systemctl disable firewalld
#Turn off firewall
systemctl stop firewalld
#Turn off SELinux, otherwise it will affect the use of samba
vi /etc/selinux/config
    #Edit content:
    SELINUX=disabled

pstree

yum install psmisc -y
#View currently running processes
pstree

Инструменты для компиляции установщика

#CentOS 1810 is installed by default
yum install -y gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel

Простая команда

#View PID by process name
pidof nginx
#Terminate by process name
pkill redis-server
killall redis-server

тсс

Mobaxterm рекомендуется для инструмента подключения SSH, который имеет функцию передачи файлов FTP

Nginx(1.16+)

Эта установка стабильна Версия (в настоящее время 1.16. * ) Официальный документ с инструкцией по установке

Добавить исходный файл nginx

#Create source file
vi /etc/yum.repos.d/nginx.repo
    #Add the following
    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx.org/packages/centos/7/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://nginx.org/keys/nginx_signing.key
    
    [nginx-mainline]
    name=nginx mainline repo
    baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
    gpgcheck=1
    enabled=0
    gpgkey=https://nginx.org/keys/nginx_signing.key

Если вы хотите установить версию основной линии в качестве установленной версии по умолчанию, выполните команду yum-config-manager --включить nginx-основную линию

устанавливать

yum install yum-utils
#The following command will install the stable version of the previous source file settings
yum install -y nginx
#View installed versions
nginx -v

Конфигурация каталога сайта

Глобальная конфигурация

#Configure execution user name
vi /etc/nginx/nginx.conf
    #Edit content:
    user www;

Добавьте конфигурацию сайта nginx для нового проекта. Это шаблон конфигурации сайта PHP. В будущем конфигурация других сайтов будет изменена и согласована на основе этого шаблона

#vi /etc/nginx/conf.d/your_project_name.conf
    #Edit content:
    Add in
    server
    {
      listen 1700;
      #listen 443 ssl http2;
      #listen [::]:443 ssl http2;
      #listen [::]:80;
      #server_name domain.com;
      
      #Character set settings can only be in the server block
      charset utf-8;
      
      index index.php index.html index.htm default.php default.htm default.html;
      root /data/wwwroot/your_project_name/public;
      
      #access_log  /data/wwwlogs/nginx/your_project_name.log;
      #error_log  /data/wwwlogs/nginx/your_project_name.error.log;
    
      #Routing configuration of laravel and ThinkPHP
      location / {
       try_files $uri $uri/ /index.php?$query_string;
      }
      
      #Running PHP files
      location ~ \.php$ {
        try_files $uri =404;
        fastcgi_index  index.php;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
      }
    
      #Forbidden files or directories
      location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
      {
        return 404;
      }
      
      location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
      {
        expires      30d;
        error_log off;
        access_log /dev/null;
      }
      
      location ~ .*\.(js|css)?$
      {
        expires      12h;
        error_log off;
        access_log /dev/null; 
      }
    }

Функция

#Test whether the configuration information has syntax problems. It can only be started after passing
nginx -t
Start up
nginx

Все инструкции

Nginx – t ා информация о конфигурации теста Nginx – режим запуска по умолчанию Nginx – V ා информация о версии дисплея, – V (большой V) отображение параметров времени компиляции Nginx – s остановка – быстрая остановка службы Nginx – s выход из Nginx – s перезагрузка

PHP(7.3)

PHP7.3

устанавливать

Installation source
yum install -y epel-release
yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
#Search for eligible packages
yum search php73
#Installing php7.3 and its extension
#Including PHP extensions such as redis, memcached, msgpack and YAF framework
yum install -y php73-php php73-php-fpm php73-php-pear php73-php-bcmath php73-php-mbstring php73-php-cli php73-php-pdo php73-php-pecl-mysql php73-php-mysqlnd php73-php-pecl-redis4 php73-php-pecl-memcached php73-php-pecl-msgpack php73-php-pecl-yaf php73-php-pecl-jsond-devel php73-php-gd php73-php-common php73-php-intl php73-php-xml php73-php-opcache php73-php-pecl-apcu php73-php-gmp php73-php-process php73-php-pecl-imagick php73-php-devel php73-php-zip php73-php-ldap php73-php-imap php73-php-pecl-mcrypt

#Installation path of the program: '/ opt / Remi / php73 /';
#Configuration file path: ` / etc / opt / Remi / php73 / PHP. Ini ';

Для настройки

cp /etc/opt/remi/php73/php.ini /etc/opt/remi/php73/php.ini.bak
#Modify PHP time zone and extended file directory path
vi /etc/opt/remi/php73/php.ini
    #Edit content:
    date.timezone = PRC
    extension_dir = "/opt/remi/php73/root/usr/lib64/php/modules/"
    
#Modify PHP FPM execution user
vi /etc/opt/remi/php73/php-fpm.d/www.conf
    #Edit content:
    user=www
    group=www
    
Empower
chown -R root:www /var/opt/remi/

#Soft chain to general catalog
ln -s /etc/opt/remi/php73/php.ini /etc/php.ini
ln -s /opt/remi/php73/root/usr/bin/php /usr/bin/php
ln -s /opt/remi/php73/root/usr/sbin/php-fpm /usr/bin/php-fpm
ln -s /opt/remi/php73/root/usr/bin/php-cgi /usr/bin/php-cgi
ln -s /opt/remi/php73/root/usr/bin/pear /usr/bin/php-pear
ln -s /opt/remi/php73/root/usr/bin/phar.phar /usr/bin/php-phar

#View the installed PHP version
php -v
#View the installed PHP extension module
php -m

Запуск PHP FPM

Start up
php-fpm
Terminate
kill -QUIT `cat /var/opt/remi/php73/run/php-fpm/php-fpm.pid`
Reboot
kill -USR2 `cat /var/opt/remi/php73/run/php-fpm/php-fpm.pid`

MySQL(8.0)

Официальное руководство по установке

Установка Yum

устанавливать

Download source
wget https://repo.mysql.com//mysql80-community-release-el7-1.noarch.rpm
Installation source
yum localinstall -y mysql80-community-release-el7-1.noarch.rpm
  #List available MySQL packages
  #yum repolist enabled | grep mysql
  #If you plan to install 5.7, perform the following two sentences to switch the default version
  #yum-config-manager --disable mysql80-community
  #yum-config-manager --enable mysql57-community
Installation
yum install -y mysql-community-server
    #Updated version
    #yum update mysql-server

#View version
mysql -V

Для настройки

vi /etc/my.cnf
    #Edit content
    [mysqld]
    #Set 3301 port
    port=3301
    #Maximum connections allowed
    max_connections=200
    #The number of connection failures allowed. This is to prevent someone from trying to attack the database system from the host
    max_connect_errors=10
    #The character set used by the server defaults to utf8
    #character-set-server=utf8
    #Default storage engine to use when creating new tables
    default-storage-engine=INNODB
    #By default, the "MySQL native password" plug-in is used for authentication, which is saved in the password processing mode of mysql5.7 to be compatible with older connection programs. By default, 8.0 is in the caching Sha2 password mode
    default_authentication_plugin=mysql_native_password
    #Set default time zone
    default-time_zone = '+8:00'

Функция

Start up
systemctl start mysqld
#Start up
systemctl enable mysqld
State of Qi
systemctl status mysqld
#View root initial password
grep 'temporary password' /var/log/mysqld.log

Log in
mysql -uroot -p
#The initial password must be modified, and the new password must contain at least 8 characters of large and small letters, numbers and special characters
#The password is processed by MySQL ﹣ native ﹣ password, saved by mysql5.7, and compatible with older connection programs. 8.0 defaults to caching ﹣ Sha2 ﹣ password
  mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Sorgo123.';
#Enter MySQL database
  mysql> use mysql;
#Set the root user to log in to any host
  mysql> update user set host='%' where user='root' and host='localhost';
  mysql> FLUSH PRIVILEGES;   
#Query user table information
  mysql> select user,host,plugin from user;

Redis(5.0)

Рекомендуемое руководство пользователя

устанавливать

cd /data/server/
wget http://download.redis.io/releases/redis-5.0.4.tar.gz
tar -zvxf redis-5.0.4.tar.gz && cd redis-5.0.4
make
#Soft link into a unified directory for multi version management
ln -s /data/server/redis-5.0.4 /data/server/redis
ln -s /data/server/redis/redis.conf /etc/redis.conf
#Soft link to command directory
ln -s /data/server/redis/src/redis-cli /usr/local/bin/redis-cli
ln -s /data/server/redis/src/redis-server /usr/local/bin/redis-server
ln -s /data/server/redis/src/redis-sentinel /usr/local/bin/redis-sentinel
#View version
redis-server -v

Для настройки

# vi /etc/redis.conf
    #Any host can access
    bind 0.0.0.0
    #Password login
    requirepass Sorgo123.
    #How background processes run
    daemonize yes

Функция

#Open by profile
redis-server /etc/redis.conf
#Enter interactive tools
redis-cli -h 127.0.0.1 -p 6379 -a Sorgo123.
#View redis process information
info server
#Shut down service
shutdown

memcached(1.4)

Установка Yum 1.4

yum install -y memcached
#View help and version
memcached -h
#Open, multiple processes can be opened according to different ports
memcached -d -p 11211 -m 150 -u www
#If it is closed, the process name including 'memcached' will be closed
pkill memcached

Параметры запуска: -D-для запуска демонов;- M-объем памяти, выделенный для Memcache, в МБ;- U-пользователь, запускающий Memcache;- L-IP-адрес отслеживаемого сервера, который может иметь несколько адресов; – P-порт для настройки прослушивания Memcache, предпочтительно выше 1024; – C-максимальное количество запущенных одновременных подключений, которое по умолчанию равно 1024; – P-файл PID для сохранения Memcache.

Сборка установка, 1.5

cd /data/server/
#Install dependency first, otherwise it cannot be compiled
yum install -y libevent-devel
#Download source code
wget http://www.memcached.org/files/memcached-1.5.13.tar.gz
#Unzip and enter directory
tar -zvxf memcached-1.5.13.tar.gz && cd memcached-1.5.13
#Execute the configuration. Only the installation directory is set here
./configure --prefix=/data/server/memcached-1.5.13/
#Compile and install
make && make install
ln -s /data/server/memcached-1.5.13 /data/server/memcached
ln -s /data/server/memcached/bin/memcached /usr/local/bin/memcached
#View installed versions
memcached -h

самба(4.8)

Installation
yum install -y samba samba-client samba-common 
#Add Samba user, user's existing user name, password specially for Samba login: sorgo
smbpasswd -a sorgo
#View added users
pdbedit -L

#Modify configuration
cp /etc/samba/smb.conf /etc/samba/smb.conf.bak
vim /etc/samba/smb.conf
    #Add directory path accessible through Samba
    [wwwroot]
             comment = website root
             path = /data/wwwroot
             valid users = sorgo
             writable = yes
             create mask = 0750
             directory mask = 0750
             
#Detect profile syntax
testparm
Start up
systemctl enable smb && systemctl enable nmb
systemctl restart smb && systemctl restart nmb
#View status
smbstatus

#Linux side use
##Test connection
smbclient -L //192.168.8.15 -U smb_user_naem
##Mount to application
mount -t cifs //192.168.8.15/wwwroot/  /smb/ -o  username=smb_user_naem,password=1234
df -h /smb
Uninstall
umount /smb

#Windows side use
\${ip}

#Precautions
*Never write Chinese in the configuration file, even Chinese comments, otherwise Windows cannot enter the directory!!!
*If the server fails to ping in windows (not because the server forbids Ping, but for unknown reasons), it cannot be connected
*Phpstrom gets stuck when opening Samba project file

Композитор(1.8)

устанавливать

#Generate composer.phar
php73 -r "copy('https://install.phpcomposer.com/installer', 'composer-setup.php');"
php73 composer-setup.php
php73 -r "unlink('composer-setup.php');"
#Move to command directory
mv composer.phar /usr/local/bin/composer
#Version and other information
composer

Устанавливать

#Set the source to domestic image, and choose one of the following two
composer config -g repo.packagist composer https://packagist.phpcomposer.com
composer config -g repo.packagist composer https://packagist.laravel-china.org
#Remove the above settings
composer config -g --unset repos.packagist
#View global configuration
composer config -gl

phpMyAdmin

phpMyAdmin Перейдите на официальный сайт и загрузите пакет PHP на сервер. Установите nginx так, чтобы он указывал на корневой каталог

cd /data/server/

#Get method 1: Download with composer (sometimes the speed is not ideal)
#composer create-project phpmyadmin/phpmyadmin
#Get method 2: WGet directly downloads from the official website (this is the way of this demonstration)
wget https://files.phpmyadmin.net/phpMyAdmin/4.8.5/phpMyAdmin-4.8.5-all-languages.zip
#Access method 3: download it in other places and upload it to the server through FTP. In principle, which is convenient and which is convenient

#Extract to current directory
unzip phpMyAdmin-4.8.5-all-languages.zip
#Soft chain for version control
ln -s phpMyAdmin-4.8.5-all-languages phpmyadmin

#Edit profile
cp phpmyadmin/config.sample.inc.php phpmyadmin/config.inc.php
vi phpmyadmin/config.inc.php
    #Here are the edits: 
    #Set any key longer than 32 bits
    $cfg['blowfish_secret'] = 'dNE9GVnon3LWSVGvhGPuZdBhb7c7RtQ3'; 

Empower
chmod -R 770  phpmyadmin/

#Nginx website configuration, using sed command to replace a key value in template configuration
#Mainly changed the listening port '8888' and log file name 'phpMyAdmin'`
cat /etc/nginx/conf.d/your_project_name.conf | sed 's/1700/8888/g' | sed 's/your_project_name\./phpmyadmin\./g' | sed 's/wwwroot\/your_project_name\/public/server\/phpmyadmin\//g' > /etc/nginx/conf.d/phpmyadmin.conf

#Check that the configuration file is correct before starting
nginx -t
Nginx restart
nginx -s reload
Visit to China
http://192.168.8.15:8888/

node.js(10,15 литра)

Китайский документ api Node.js устанавливается следующими способами:

  1. Установка EPEL с исходным кодом Yum (в настоящее время версия 6.16);
  2. Двоичная установка;
  3. Компиляция и установка исходного кода;

Теперь мы представим два последних метода, которые также богаты выбором версий

Двоичная установка (10.15.3) (рекомендуется)

Это можно загрузить и использовать

cd /data/server/
#Download binary package, about 12m
wget https://nodejs.org/dist/v10.15.3/node-v10.15.3-linux-x64.tar.xz
#Unzip. Note that the unzip command is different from the file at the end of unzip '. GZ'
tar -xJvf node-v10.15.3-linux-x64.tar.xz
Soft chain
ln -s node-v10.15.3-linux-x64 node
ln -s /data/server/node/bin/node /usr/local/bin/node
ln -s /data/server/node/bin/npm /usr/local/bin/npm
ln -s /data/server/node/bin/npx /usr/local/bin/npx

#View version
node -v
npm -v

Сборка установка (10.15.3)

Процесс компиляции очень медленный, около часа личного тестирования

cd /data/server/
#Download the source code, about 35m
wget https://nodejs.org/dist/v10.15.3/node-v10.15.3.tar.gz
tar -zvxf node-v10.15.3.tar.gz && cd node-v10.15.3
#Execute configuration script
./configure
#Compile and install
make && make install
#View version
node -v
npm -v

пряжа(1.15)

Официальные установочные документы

#Add Yum source for yarn
curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo
#To install, make sure nodejs is installed
yum install -y yarn
#View version
yarn -v