: :

ПнВтСрЧтПтСбВс

2017-11-22 19:27:08 4273 0

Установка и первоначальная настройка LEMP (Nginx,Mysql,PHP) на Gentoo linux

Gentoo один из самых быстрых дистрибутивов Linux, потому что он является ориентированным на сборку пакетов из исходных ходов. Произведем установку стека LEMP на Gentoo linux

Перед установкой веб-сервера Nginx необходим обновить систему и установить локаль

Добавляем необходимую локаль в файле /etc/locale.gen

#fr_FR@euro ISO-8859-15
#it_IT ISO-8859-1
en_US.UTF-8 UTF-8
ru_RU.UTF-8 UTF-8

Сгенерируем локаль из файла /etc/locale.geb с помощью команды:

locale-gen

 * Generating locale-archive: forcing # of jobs to 1
 * Generating 2 locales (this might take a while) with 1 jobs
 *  (1/2) Generating en_US.UTF-8 ...                                      [ ok ]
 *  (2/2) Generating ru_RU.UTF-8 ...                                      [ ok ]
 * Generation complete

Проверяем доступные локали:

eselect locale list

Available targets for the LANG variable:
  [1]   C
  [2]   POSIX
  [3]   en_US.utf8
  [4]   ru_RU.utf8
  [ ]   (free form)

Выбираем необходимую (ru_RU.utf8):

eselect locale set 4

Setting LANG to ru_RU.utf8 ... Run ". /etc/profile" to update the variable in your shell.

Обновляем переменные окружения:

. /etc/profile

Проверяем переменные окружения:

locale

LANG=ru_RU.utf8
LC_CTYPE="ru_RU.utf8"
LC_NUMERIC="ru_RU.utf8"
LC_TIME="ru_RU.utf8"
LC_COLLATE="ru_RU.utf8"
LC_MONETARY="ru_RU.utf8"
LC_MESSAGES="ru_RU.utf8"
LC_PAPER="ru_RU.utf8"
LC_NAME="ru_RU.utf8"
LC_ADDRESS="ru_RU.utf8"
LC_TELEPHONE="ru_RU.utf8"
LC_MEASUREMENT="ru_RU.utf8"
LC_IDENTIFICATION="ru_RU.utf8"
LC_ALL=

Обновляем систему

emerge --sync

emerge --update --deep --with-bdeps=y @world

Установка Nginx

Выведем модули, с которыми веб-сервер будет установлен по-умолчанию:

emerge -pv nginx

[ebuild  N     ] www-servers/nginx-1.12.1::gentoo  USE="http http-cache http2 ipv6
pcre ssl -aio -debug -libatomic (-libressl) -luajit -pcre-jit -rtmp (-selinux)
 -threads -vim-syntax" NGINX_MODULES_HTTP="access auth_basic autoindex browser
  charset empty_gif fastcgi geo gzip limit_conn limit_req map memcached proxy
   referer rewrite scgi split_clients ssi upstream_hash upstream_ip_hash
    upstream_keepalive upstream_least_conn upstream_zone userid uwsgi -addition
     -auth_ldap -auth_pam -auth_request -cache_purge -dav -dav_ext -degradation
      -echo -fancyindex -flv -geoip -gunzip -gzip_static -headers_more 
      -image_filter -lua -memc -metrics -mogilefs -mp4 -naxsi -perl -push_stream 
      -random_index -realip -secure_link -security -slice -slowfs_cache -spdy
       -sticky -stub_status -sub -upload_progress -upstream_check -xslt" 
       NGINX_MODULES_MAIL="-imap -pop3 -smtp" NGINX_MODULES_STREAM="-access -geo 
       -geoip -limit_conn -map -realip -return -split_clients -ssl_preread 
       -upstream_hash -upstream_least_conn -upstream_zone" 1 023 KiB

Total: 1 package (1 new), Size of downloads: 1 023 KiB

 * IMPORTANT: 10 news items need reading for repository "gentoo".
 * Use eselect news read to view new items.

Устанавливаем Nginx и указываем модули, которые хотим добавить или удалить из параметров сборки по-умолчанию

USE="vim-syntax" NGINX_MODULES_HTTP="fastcgi" emerge -av nginx

Запускаем веб-сервер

/etc/init.d/nginx start

Добавляем в автозагрузку

rc-update add nginx

Установка PHP

Для использования языка PHP с веб-сервером Nginx необходимо будет установить модуль PHP-FastCGI Process Manager (FPM) и другие PHP расширения

Создаем файл /etc/portage/package.use/php и в нем указываем необходимые модули

cat /etc/portage/package.use/php

dev-lang/php fpm cgi curl gd imap pdo mysql mysqli zip json xcache apc \
 zlib zip truetype -apache2 -ipv6

Выполняем обновление конфигурационных файлов

etc-update

Scanning Configuration files...
The following is the list of files which need updating, each
configuration file is followed by a list of possible replacement files.
1) /etc/init.d/devfs (1)
2) /etc/portage/package.use/php (1)
Please select a file to edit by entering the corresponding number.
        (don"t use -3, -5, -7 or -9 if you"re unsure what to do)
        (-1 to exit) (-3 to auto merge all files)
                     (-5 to auto-merge AND not use "mv -i")
                     (-7 to discard all updates)
                     (-9 to discard all updates AND not use "rm -i"): 1

Выбираем вариант со слиянием файлов (-3) жмем "Enter" и при вопросе о перезаписи файлов на каждый отвечаем "y"

Теперь можем собрать пакет с указанными нами модулями

Устанавливаем PHP

emerge -av php

Изменить настройки php-fpm можно в файле /etc/php/fpm-php7.0/php-fpm.conf и /etc/php/fpm-php7.0/fpm.d/www.conf

Запускаем php-fpm

/etc/init.d/php-fpm start

Добавляем в автозагрузку

rc-update add php-fpm

Настройка Nginx для работы с php-fpm

Изменяем секцию server:

 server {
                listen *:80;
                server_name _default;

                access_log /var/log/nginx/localhost.access_log main;
                error_log /var/log/nginx/localhost.error_log info;

                root /var/www/;
                #index index.html;
                location ~ \.php$ {
                index index.php;
                try_files $uri =404;
                include /etc/nginx/fastcgi.conf;
                fastcgi_pass 127.0.0.1:9000;
                }
        }

  • listen *:80 - слушать все адреса на порту 80;
  • server_name _default - обрабатывать запросы с любым именем http заголовка HOST;
  • access_log, error_log - указываем путь хранения и формат логов;
  • root - директория с файлами веб-сайта;
  • location ~ .\php$ - настройка для обработки запросов с обращением к php файлам
  • index index.php - файл для обработки по-умолчанию
  • try_files $uri =404 - порядок обработки запроса
  • include /etc/nginx/fastcgi.conf - включения файла настроек fastcgi
  • fastcgi_pass 127.0.0.1:9000 - перенаправление запроса на php бэкэнд

Перезапускаем Nginx

/etc/init.d/nginx restart

Для проверки работы Nginx с PHP, в папке указанной в секции root файла конфигурации Nginx создаем файл index,php со следующим содержанием:

<?php phpinfo(); ?>

Подключаемся к веб-серверу через браузер и должны увидеть вывод phpinfo

Вывод phpinfo

Установка Mysql

Устанавливать будем Mariadb, форк Mysql

emerge -av mariadb

Выполняем команду для настройки mariadb:

emerge --config mariadb

Будет запрос на установку пароля для root, оставляем пароль пустым (установим его дальше)

Запускаем демона:

/etc/init.d/mysql start

Добавляем в автозагрузку:

rc-update add mysql

После установки произведем первоначальную настройку Mariadb, запускаем скрипт для настройки:

mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we"ll need the current
password for the root user.  If you"ve just installed MariaDB, and
you haven"t set the root password yet, the password will be blank,
so you should just press enter here.


Enter current password for root (enter for none): 

----------------------
Текущий пароль root - пустой
----------------------

OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] 
----------------------
Устанавливаем пароль для root
----------------------
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y

----------------------
Удаление анонимных пользхователей
----------------------

 ... Success!

Normally, root should only be allowed to connect from "localhost".  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
----------------------
Отклю.чаем возможность подключения root удаленно
----------------------

 ... Success!

By default, MariaDB comes with a database named "test" that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
----------------------
Удаление тестовой базы данных
----------------------

 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
----------------------
Перезапуск привелегий
----------------------

 ... Success!

Cleaning up...

All done!  If you"ve completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

Пробуем подключиться к базе данных:

mysql -U root -p

Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.1.26-MariaDB Source distribution

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type "help;" or "\h" for help. Type "\c" to clear the current input statement.

MariaDB [(none)]> 

Mariadb установлен и настроен






Введите ответ:

+

=