Install LEMP on CentOS 6.*

Table of Content

Передбачається, що сама CentOS вже встановлена в мінімальній конфігурації.
Далі буде інформація, що відноситься до повного налаштування веб-серверу.

1. Зміна hostname серверу

# hostname
CentOS-70-64-minimal

Дана назва нам нічого не говорить, а якщо в нас декілька серверів, тоді взагалі скоро заплутаємось в них.
Краще брати назву яку пропонує дата-центр, в подальшому це мінімізує більшість помилок. Переглянути назву сервера можна в панелі адміністрування, це може бути щось на кшталт triton567 або #400055.
Якщо слово-приставка біля цифр є – залишаємо назву, якщо немає – додаємо назву компанії клієнта (md400055).

Використаємо sysctl для зміни hostname

# sysctl kernel.hostname=md400055
kernel.hostname = md400055

3. Налаштовуємо timezone

Changing The Time Zone In Linux (Command Line)

4. Збільшуємо обмеження на кількість відкритих файлів

http://blog.agere.com.ua/sqlstate-hy000-general-error-23-out-of-resources-when-opening-file-tmp-sql_203f_0-myd-errcode-24-too-many-open-files/

2. Відключення SSH доступу для root

Важливо! Не відключайте доступ для root поки остаточно не переконаєтесь, що можна виконати логін від іншого користувача.

Додаємо користувача

# useradd admin
# passwd admin
Changing password for user admin.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

Для Debian спочатку потрібно встановити відповідний пакет, в CentOS цього робити не потрібно

# apt-get install sudo

Надаємо доступ виконувати su або sudo до root

# chmod +w /etc/sudoers
# vi /etc/sudoers
...
root    ALL=(ALL)       ALL
popov   ALL=(ALL)       NOPASSWD: ALL
...
# chmod -w /etc/sudoers

Пробуємо підключитись за допомогою SSH-клієнта до севрера під новим користувачем. Якщо авторизація пройшла успішно, можна переходити до наступного кроку.

Відключаємо доступ для root через SSH
Відкриваємо файл залогінившись під root, розкоментуємо конфіг та змніюємо значення з yes на no

# vi /etc/ssh/sshd_config
...
PermitRootLogin no
...

Далі потрібно перезавантажити sshd сервіс

# service sshd restart

Тепер ніхто не зможе підібрати пароль і залогінитись під root

2. Встановлення Nginx (last version)

UPD. Для CentOS 7.*
Перевіряємо чи доступний пакет для встановлення

# yum info nginx
...
No package nginx available.

Якщо результат як вище, виконуємо наступний крок. Якщо пакет доступний в репозиторію, пропускаємо корок, і переходимо зразу до встановлення.

# yum install epel-release
# yum update

Step #1: Install nginx repo

For CentOS 6.*
Type the following wget command to install nginx yum configuration file:

# cd /tmp
CentOS Linux v6.x user type the following command:
# rpm -ivh nginx-release-centos-6-0.el6.ngx.noarch.rpm

For Debian 7.*
http://www.devops.zone/webserver/install-nginx-1-6-0-on-debian-wheezy/

Step #2: Install nginx web-server

Type the following yum command to install nginx web-server:
# yum install nginx
Sample outputs:

Loaded plugins: product-id, rhnplugin, security, subscription-manager
Updating certificate-based repositories.
Unable to read consumer identity
nginx | 1.3 kB 00:00
nginx/primary | 4.8 kB 00:00
nginx 33/33
Setting up Install Process
Resolving Dependencies
–> Running transaction check
—> Package nginx.x86_64 0:1.2.6-1.el6.ngx will be installed
–> Finished Dependency Resolution

Dependencies Resolved

================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
nginx x86_64 1.2.6-1.el6.ngx nginx 361 k

Transaction Summary
================================================================================
Install 1 Package(s)

Total download size: 361 k
Installed size: 835 k
Is this ok [y/N]: y
Downloading Packages:
nginx-1.2.6-1.el6.ngx.x86_64.rpm | 361 kB 00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
Installing : nginx-1.2.6-1.el6.ngx.x86_64 1/1
———————————————————————-

Thanks for using NGINX!

Check out our community web site:
* http://nginx.org/en/support.html

If you have questions about commercial support for NGINX please visit:
* http://www.nginx.com/support.html

———————————————————————-
Installed products updated.
Verifying : nginx-1.2.6-1.el6.ngx.x86_64 1/1

Installed:
nginx.x86_64 0:1.2.6-1.el6.ngx

Complete!

Step #3: Turn on nginx service

Type the following command:
# systemctl enable nginx.service

How do I start/stop/restart nginx web-server?

Type the following czommands:
CentOS <7.*

# service nginx start
# service nginx stop
# service nginx restart
# service nginx status
# service nginx reload

CentOS >=7.*

# systemctl start nginx
# systemctl stop nginx
# systemctl restart nginx
# systemctl status nginx
# systemctl reload nginx

Step #4: Configuration files

Default configuration directory: /etc/nginx/
Default SSL and vhost config directory: /etc/nginx/conf.d/
Default log file directory: /var/log/nginx/
Default document root directory: /usr/share/nginx/html
Default configuration file: /etc/nginx/nginx.conf
Default server access log file: /var/log/nginx/access.log
Default server access log file: /var/log/nginx/error.log

To edit the nginx configuration file, enter:

# vi /etc/nginx/nginx.conf

Set or update worker_processes as follows (this must be set to CPU(s) in your system. Use the lscpu | grep ‘^CPU(s)’ command to list the number of CPUs in the server)

worker_processes 2;
worker_rlimit_nofile 20960;
worker_priority -10;
events {
    worker_connections  1024;
    use epoll;
    multi_accept on;
}
#Turn on gzip support:
http {
   ...
   gzip on;
   server_names_hash_max_size 1024;
   client_max_body_size 600m;
   #Add config directory:
   include /etc/nginx/sites-enabled/*.conf;
}

Save and close the file.

Create directory for links and sites config

# mkdir /etc/nginx/sites-enabled
# mkdir /etc/nginx/sites-available
# chmod -R 655 /etc/nginx/sites-*

Create user for site

# useradd nb-style
# passwd nb-style

Create directory for sites

# mkdir -p /web/sites/nb-style
# cd /web/sites/nb-style
# mkdir data
# mkdir logs
# mkdir tmp
# cd data
# mkdir nb-style
# ln -s /web/sites/nb-style/data/nb-style /web/sites/nb-style/data/production
# vi production/index.php
<?php
phpinfo();
# chown -R md-fashion:nginx /web/sites/nb-style

Edit the file /etc/nginx/sites-available/nb-style.conf, enter:
# vi /etc/nginx/sites-available/nb-style.conf

server {
   #Set IP address and TCP port number:
   listen 80;
   #listen 443;
   # Uncomment if need ssl certified
   #ssl on;
   #ssl_certificate /etc/nginx/ssl/nb-style_com_ua.crt;
   #ssl_certificate_key /etc/nginx/ssl/nb-style.key;
   #ssl_session_cache shared:SSL:10m;
   #ssl_session_timeout 10m;
   #set_real_ip_from 127.0.0.1;
   #real_ip_header X-Forwarded-For;
   #port_in_redirect off;
   #Set server name:
   server_name nb-style.com.ua www.nb-style.com.ua;
   root /web/sites/nb-style/data/production;
   access_log /web/sites/nb-style/logs/nb-style.com.ua.access.log;
   error_log /web/sites/nb-style/logs/nb-style.com.ua.error.log;
   index index.php;
   location ~ ((/app/|/pkginfo/|/var/|report/config.xml)|/\.svn/|/.htaccess.+) {deny all;}
   location /minify/ {rewrite ^/minify/([0-9]+)(/.*\.(js|css))$ /lib/minify/m.php?f=$2&amp;d=$1 last;}
   location /skin/frontend/blank/default/favicon.ico {rewrite ^/skin/frontend/blank/default/favicon.ico$ /favicon_avto.ico last;}
   location /favicon.ico {rewrite ^/favicon.ico$ /favicon_avto.ico last;}
   error_page  404  /404.html;
   location ~ (\.php|/downloader/?|/report/?|/404/?|/js/?)$ {
      if ($request_uri ~ /(downloader|report)$){rewrite  ^(.*)$ $1/ permanent;}
      fastcgi_index index.php;
      fastcgi_read_timeout 800;
      fastcgi_param SERVER_PORT 80;
      include /etc/nginx/fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      if (-e $request_filename) {
         fastcgi_pass unix:/web/sites/nb-style/logs/php-fpm-nb-style.sock;
      }
   }
   location / {
      if ($request_uri ~* &quot;\.(ico|css|js|gif|jpe?g|png)$&quot;) {expires max;}
      include /etc/nginx/fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root/index.php;
      fastcgi_param SCRIPT_NAME /index.php;
      fastcgi_read_timeout 80000;
      fastcgi_param SERVER_PORT 80;
      #cache
      ###include /etc/nginx/conf.d/cache.conf;
      if (!-f $request_filename) {
     fastcgi_pass unix:/web/sites/nb-style/logs/php-fpm-nb-style.sock;
         break;
     }
   }
   location /magmi/ {
      auth_basic &quot;Restricted&quot;;
      auth_basic_user_file $document_root/.htpasswd;
      autoindex on;
   }
}

Для віртуальних хостів які використовують SSL обов’язково вказувати:

listen 443 ssl;

інакше виникає помилка
Код помилки: ssl_error_rx_record_too_long

Save and close the file. Add link for config

# ln -s /etc/nginx/sites-available/md-fashion.conf /etc/nginx/sites-enabled/md-fashion.conf

Start the server:
# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# systemctl start nginx
Verify that everything is working:
# netstat -tulpn | grep :80
# ps aux | grep nginx

Optional: Firewall configuration: Open TCP port # 80

You need to enable access to your server on port 80 as it is currently being blocked by iptables.

# sudo /sbin/iptables -I INPUT -p tcp -m tcp –dport 80 -j ACCEPT

OR

Edit the file /etc/sysconfig/iptables, enter:
# vi /etc/sysconfig/iptables
Add the following lines, ensuring that they appear before the final LOG and DROP lines for the INPUT chain to open port 80:

-A INPUT -m state –state NEW -p tcp –dport 80 -j ACCEPT

Save and close the file. Finally, restart the firewall:
# service iptables restart

3. Встановлення PHP & MySQL (last version)

UPD. Інструкція нижче створювалась для CentOS 6.*, коли PHP 5.4 ще не було в офіційних репозиторіях. На даний момент є реліз CentOS 7.* і в ній доступні необхідні нам пакети PHP.
Перевірте чи влаштовує вас версія PHP, виконайте наступні команди для автоматичного встановлення і можна переходити до безпосереднього налаштування PHP
UPD2. Вже наявна версія PHP 5.6 та PHP 7 в репозиторіях.

Офіційні джерела не рекомендують використовувати Webtatic

The webtatic repo contains many packages with names that conflict with the names of packages in CentOS base and updates repos. This means that it replaces packages supplied by CentOS without warning. Examine your /var/log/yum.log and see what else got updated at the same time as the php packages were installed (or afterwards). Use rpm -qi $packagename to check to make sure that the buildhost is a CentOS one and that the signing key is the CentOS one for each of those.

The IUS Community repo is a better source of replacement packages since they are all named differently than the ones CentOS supply so you have to take explicit action to install them.

Тоді виконаємо відповідно інших рекомендацій.
Зверніть увагу там є посилання на wizard який дасть правильний порядок команд для вашої версії CentOS

CentOS 7 provides PHP version 5.4 in its official repository

Command to install the EPEL repository configuration package:

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

Command to install the Remi repository configuration package:

yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm

Command to install the yum-utils package (for the yum-config-manager command):

yum install yum-utils

You want a single version which means replacing base packages from the distribution

PHP version 5.6 packages are available for CentOS 7 in remi-php56 repository

Command to enable the repository:

yum-config-manager --enable remi-php56

Command to upgrade (the repository only provides PHP):

yum update

Command to install additional packages:

yum install php-xxx

Command to check the installed version and available extensions:

php --version
php --modules
# yum info php
# yum install php php-fpm php-gd php-mysql php-mbstring php-xml php-mcrypt php-soap php-intl

Для Debian

# apt-get install php5 php5-curl php5-gd php5-mcrypt php5-mysql -y

або виконайте наступні інструкції

http://webees.me/how-to-install-php-5-4-and-mysql-5-5-in-centos-6-4-via-yum/
http://turnkeye.com/blog/nginx-for-magento/

Підключаємо додаткові репозиторії

Перевіряємо список репозиторіїв

# yum repolist

Ви можете знайти встановлені репозиторії

Вмикаємо репозиторії і встановлюємо

# vi /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&amp;arch=$basearch
failovermethod=priority
enabled=0 # 1 -&gt; 0 disable
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

 

# vi /etc/yum.repos.d/rpmforge.repo
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
enabled = 0 # 1 -&gt; 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

встановіть їх відповідно з опціями, які ви використовуєте.
спробуємо отримати інформацію про php

# yum --enablerepo=epel,remi,rpmforge info php
Name : php
Arch : x86_64
Version : 5.4.22
Release : 1.el6.remi
Size : 2.7 M
Repo : remi
Summary : PHP scripting language for creating dynamic web sites
URL : http://www.php.net/
License : PHP and Zend and BSD
Description : PHP is an HTML-embedded scripting language. PHP attempts to make it
: easy for developers to write dynamically generated web pages. PHP also
: offers built-in database integration for several commercial and
: non-commercial database management systems, so writing a
: database-enabled webpage with PHP is fairly simple. The most common
: use of PHP coding is probably as a replacement for CGI scripts.
:
: The php package contains the module (often referred to as mod_php)
: which adds support for the PHP language to Apache HTTP Server.
OK, продовжимо, встановлюємо PHP &amp; PHP-FPM
# yum --enablerepo=epel,remi,rpmforge install php php-fpm php-gd php-mysql php-mbstring php-xml php-mcrypt php-soap

Ініціалізація
Введіть php -v, щоб переконатись, що все становилось правильно.

Налаштування PHP-FPM

short_open_tag = On
date.timezone = Europe/Kiev

Налаштування PHP-FPM 
Для кращого контролю, налаштування проводимо відповідно до стретегії один pool на один проект.
В директорії /etc/php-fpm.d перейменовуємо www.conf

# cd /etc/php-fpm.d
# mv www.conf www.conf.bak

Налаштовуємо конфіг для проекту

# vi md-fashion.conf
;include=etc/fpm.d/*.conf
[global]
pid = /web/php-5.4/run/md-fashion.pid
error_log = /web/sites/md-fashion/logs/php-fpm-md-fashion.log
;log_level = notice
;emergency_restart_threshold = 0
;emergency_restart_interval = 0
;process_control_timeout = 0
daemonize = yes
[md-fashion]
prefix =
listen = /web/sites/$pool/logs/php-fpm-$pool.sock
;listen = 127.0.0.1:9000
listen.backlog = -1
;listen.allowed_clients = 127.0.0.1
listen.owner = $pool
listen.group = $pool
listen.mode = 0666
user = $pool
group = $pool
pm = dynamic
pm.max_children = 8
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 8
pm.max_requests = 1000
;pm.status_path = /status
;ping.path = /ping
;ping.response = pong
#request_terminate_timeout = 180s
request_terminate_timeout = 0
request_slowlog_timeout = 20
slowlog = /web/sites/$pool/logs/$pool.log.slow
;rlimit_files = 1024
;rlimit_core = 0
;chroot = /web/sites/$pool
;chdir = http_pub/arti.if.ua
;catch_workers_output = no
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /web/sites/$pool/tmp
env[TMPDIR] = /web/sites/$pool/tmp
env[TEMP] = /web/sites/$pool/tmp
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_admin_value[open_basedir] = /web/sites/$pool
php_admin_value[upload_tmp_dir] =/web/sites/$pool/tmp
php_admin_value[session.save_path]=/web/sites/$pool/tmp
php_admin_flag[safe_mode] = off
php_flag[display_errors] = off
php_admin_value[error_log] = /web/sites/$pool/logs/fpm-php-$pool.log
;php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 512M
php_admin_value[max_execution_time] = 0
php_admin_value[max_input_time] = 0
php_admin_value[upload_max_filesize] = 100M
php_admin_value[post_max_size] = 100M

Вмикаємо автозавантаження після перезавантаження серверу

# systemctl enable php-fpm.service

3. Встановлення MySQL(last version)

Для Debian використовувати дану статтю https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-12-04

В CentOS 7.* MySQL чомусь не встановлений в репозиторії по замовчуваню. Необхідно додати вручну. Повна версія тут

Add the Repository

Most Linux distributions will already provide the MySQL packages in the default distribution repository. The following steps will describe adding an official YUM repository provided by Oracle which will provide the latest version available.

The YUM repository configuration can be downloaded from the MySQL website.

http://dev.mysql.com/downloads/repo/yum/

Choose the desired distribution (Red Hat Enterprise Linux 7 / Oracle Linux 7 for this tutorial) and click Download.

The download link can be retrieved without registering for an Oracle account. Locate the No thanks, just start my download link and pass the link URL as a parameter to rpm.

$ sudo rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm

Install MySQL Packages

MySQL server can now be installed using YUM. The MySQL client package will be included with the server package.

$ sudo yum -y install mysql-community-server

Any required changes to MySQL configuration file, /etc/my.cnf, should be made after the install has completed.

Починаючи з MySQL 5.7 root пароль можна глянути в логах (детально тут)

# grep 'temporary password' /var/log/mysqld.log

Start MySQL Server

The MySQL daemon should be enabled to start on boot.

$ sudo systemctl enable mysqld

The server can now be started.

$ sudo systemctl start mysqld

Secure MySQL
Once the MySQL server has started, the service will then need to be secured. The mysql_secure_installation script will assist with this process by presenting several questions. It is recommended to accept the default action for all questions which is yes.

$ sudo /usr/bin/mysql_secure_installation
  • Set root password? [Y/n] Y
  • Remove anonymous users? [Y/n] Y
  • Disallow root login remotely? [Y/n] Y
  • Remove test database and access to it? [Y/n] Y
  • Reload privilege tables now? [Y/n] Y

Firewall Rules

It is highly recommended that the ProfitBricks firewall and/or local Linux firewall be used to restrict access to the MySQL server. Only hosts requiring connectivity to the MySQL server should be granted network access.

MySQL listens on TCP port 3306 by default.

If the CentOS firewall is enabled, then a rule allowing access to the MySQL server on port 3306/tcp from host192.0.2.10 can be added.

firewall-cmd --permanent --zone=trusted --add-source=192.0.2.10/32
firewall-cmd --permanent --zone=trusted --add-port=3306/tcp
firewall-cmd  --reload

Create Database User

Never configure a web application to use the root user to access MySQL. An individual, application-specific user should be used instead. First log into MySQL with an administrative user.


$ mysql -u root -p mysql

The following steps will describe creating a new database named appdb and granting the appuser full access to the new database. Adjust the hostname from which the user will be connecting and password as necessary.


mysql> create database appdb;
mysql> grant all on appdb.* to 'appuser'@'localhost' identified by 'password';
mysql> quit

You should test access to the database with the new application user.


mysql -u appuser -p -h localhost appdb

Редагуємо конфіг
# vi /etc/my.cnf
[mysqld]
.
.
#add bellow
character-set-server = utf8
skip-character-set-client-handshake

# service mysqld restart
mysql> staus
.
.
# check them like this
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8

Leave a Reply

Your email address will not be published. Required fields are marked *