Archive

Posts Tagged ‘nginx’

Meet the systemd, or short introduction

April 10th, 2016 No comments

systemd – is initialization system for other demons to Linux, which came to replace the previously used /sbin/init. Its special feature is the intensive parallelization while start services at boot time, which can significantly speed up the launch of the operating system.
The name comes from the Unix suffix «d» to the demon (c) Wikipedia. In this article, we will speak only about CentOS, but of course, this will also be true for other systems.

A problem often encountered in systemd, when even with seemingly correct configuration, the service does not start. Looking through the logs, you can understand that mistakes are usually standard – for the example of httpd he can not listen to the port, or resolve ldap user. After many experiments, we found the optimal configuration scripts that run in servers correctly.
All startup scripts are in the directory /lib/systemd/system

Apache

The file is called httpd.service. The problem is that he did not work until until network subsystem will not loaded and resolving ldap users. For Apache start network-online.target, nss-lookup.target and nss-user-lookup.target must be loaded before Apache. It is easy to understand, if you take a look on config file below:

[Unit]
Description = The Apache HTTP Server
After = network-online.target remote-fs.target nss-lookup.target nss-user-lookup.target
Documentation = man: httpd (8)
Documentation = man: apachectl (8)

[Service]
Type = notify
EnvironmentFile = /etc/sysconfig/httpd
ExecStart = /usr/sbin/httpd $ OPTIONS -DFOREGROUND
ExecReload = /usr/sbin/ httpd $ OPTIONS -k graceful
ExecStop = /bin/kill -WINCH $ {MAINPID}
KillSignal = SIGCONT
PrivateTmp = true

[Install]
WantedBy = multi-user.target

Configuring Apache additional instances in systemd

In order to configure Apache to work on multiple ports at once (additional instances or “profiles”), you need to do a little creative action.

Create Apache configs

Additional Apache will listen to another port, so we need an another config file, which will be described. For example, here is this one.

Listen 192.168.150.214:8001
Include conf/Includes/ *. Conf
Include conf/hosting/ *. Conf
Include conf/vhosts/ *. Conf

CustomLog "/var/log/apache/access1.log" combined env =! Dontlog
ErrorLog "/var/log/apache/error1.log"

User apache
Group apache

PidFile /var/run/httpd/httpd1.pid

You must specify a folder with our configs, by analogy with the standard the httpd.conf, be sure to rename the name of the log, enter the user/group of the web server and the pid-file. In fact nothing more is needed for configuration. Let’s call httpd1.conf file for port 8001, httpd2.conf for port 8002 and then more, by analogy, if you need more.

Edit files with parameters

To get started, copy a file from the folder / etc / sysconfig

# Cp httpd httpd1

If you need to do more profiles, copy as needed.
Next, edit the copied a file. Do not touch the default file. All that should be in it, it’s two lines:

OPTIONS = -f conf / httpd1.conf
LANG = C

More, in fact, do not need anything. As you guessed, conf / httpd1.conf is a workpiece Apache config, which we did in the preceding paragraph.

Make and run the service

So, go to the folder with start scripts systemd

# Cd /lib/systemd/system

Copy the current service and a file called names by analogy with configs and files from the sysconfig

# Cp httpd.service httpd1.service.

Edit the config file which we COPIED before, leaving intact a default one

# EnvironmentFile = /etc/sysconfig/httpd

Replace the created us

# EnvironmentFile = /etc/sysconfig/httpd1

Save, switch service on

# Systemctl enable httpd1

Run it

# Systemctl start httpd1.service

Or so – also fulfills

# Systemctl start httpd1

So, you have additional instance Apache.

nginx

nginx.service adjusted by analogy – the main thing that against official documentation in “After” was present network-online.target. Also, it is important (applies also, and apache) remote-fs.target option – any occurred after loading it as a Web server files can take, for example, GlusterFS.

[Unit]
Description = The NGINX HTTP and reverse proxy server
After = syslog.target network-online.target remote-fs.target nss-lookup.target

[Service]
Type = forking
PIDFile = /run/nginx.pid
ExecStartPre = /usr/sbin/nginx -t
ExecStart = /usr/sbin/nginx
ExecReload = /bin/kill -s HUP $ MAINPID
ExecStop = /bin/kill -s QUIT $ MAINPID
PrivateTmp = true

[Install]
WantedBy = multi-user.target

Zabbix

Similarly configs web server, you need to change in the default script

After = network.target
On
After = network-online.target

Commands

For easy management, systemd has a large number of commands. Know all of them is not necessarily, but here is a list of basic and necessary good to know.

List

In the case if you edited boot scripts and other components systemd, you can restart it by command:

systemctl daemon-reload

Generate a report on the boot systemd and put it in a file (by the way, it is very useful for understanding the operation of systemd)

systemd-analyze plot> /home/vtorov/boot.svg

Take a look what services are loaded in systemd, or enabled while system start

systemctl list-units --type service

As above, but more and shows the “Target”

systemctl list-units

Switching on and off, reload/restart the service, or other actions (see them below)

systemctl <action> <object>

That is, for example,

systemctl restart httpd

Where restart is an action, but httpd is an object. The list of actions below.

Actions

reload
restart
enable
disable
stop
start
status

By the way, old chkconfig, redirecting their actions into systemd, but because it will soon be expelled from the CentOS, then to use it is not necessary to devote more time and systemd.

Тюнинг nginx: заставляем веб-сервер работать быстрее

March 28th, 2012 No comments

Сегодня речь пойдет о небольшой оптимизации веб-сервера nginx. Задача – уменьшить время загрузки веб-странички у клиентов. Решение – небольшой тюнинг конфигов nginx.

Разбираем конфиг nginx. По умолчанию находится в /usr/local/nginx/conf/nginx.conf  или в /etc/nginx/nginx.conf 🙂 В моем случае это первый вариант.

Редактируем:

# nano /usr/local/nginx/conf/nginx.conf

Видим конфиг:

# Пользователь, от которого работает nginx
user www-data www-data;
# Кол-во процессов – ставится значение, равное кол-ву ядер в системе
worker_processes 4;

# Пишем логи
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;

# Кол-во соединений
events {
worker_connections 2048;
}

http {
# Подключаем mime
include mime.types;
default_type application/octet-stream;

# Запись Access-логов. По желанию. Можно добавлять в вирт. хосты
#access_log logs/access.log main;

# Лучше включить – значительно повышает скорость отдачи контента.
sendfile on;

# Каждому свое. Для блога на wordpress хорошо подходит параметр, равный 15.
keepalive_timeout 15;

# Если мы используем проксирование, то параметры удобнее вывести в отдельный файл:
include /etc/nginx/proxy.conf;

# Выключаем версию сервера
server_tokens off;

# Подключаем файл с виртуальными хостами
include /etc/nginx/sites-enabled/*;

# Параметры сжатия gzip
gzip on;
gzip_buffers 4 8k;
gzip_comp_level 7;
gzip_proxied any;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

# Включаем кеширование заголовков
expires max;

# Позволяет передавать файл в полных пакетах
tcp_nopush on;
# Разрешает/запрещает tcp_nodelay при переходе в состояние keep_alive
tcp_nodelay on;
}

Пока всё. Отредактируем proxy.conf:

# nano /etc/nginx/proxy.conf

# Переадресация прокси
proxy_redirect off;
# Передаем через прокси внешний IP клиента
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Остальные параметры proxy
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;

nginx+apache+memcached+xcache: fast web-server

March 26th, 2012 No comments

Со временем каждый интернет-проект ждет неизбежное: либо он остается в тени и неизвестности, либо становится популярным и посещаемым. Посещаемость это хорошо, но готов ли к этому ваш сервер? С повышением нагрузки на проект обычно используют модель back-end+front-end, а именно связка nginx+apache.  Как это работает: все внешние соединения на себя принимает nginx, за отдачу статического содержимого (все изображения, стили, html, аудио и видео) отвечает так же он. Apache же в свое время отвечает только за статическое содержимое и во “внешку” не смотрит. Что бы их “связать” в nginx необходимо будет настроить проксирование.

Обновляем кеш репозитариев:

# aptutude update

Устанавливаем Apache, php, mysql и необходимые им модули:

# aptitude -y install apache2 php5 mysql-server libapache2-mod-auth-mysql php5-mysq mysql-admin libphp-jpgraph php5-imagick

Настраиваем Apache:

# nano /etc/apache2/ports.conf

По умолчанию Apache слушает внешние соединения на 80 порт. Исправим это, заменив Listen 80 на:

Listen localhost:8080

Далее отредактируем конфиг apache2.conf и вставим в самый низ строчку NameVirtualhost *:8080

# nano /etc/apache2/apache2.conf

Создадим новый VirtualHost в sites-available:

# nano /etc/apache2/sites-available/sitename.ru.conf

Вписываем туда:

<VirtualHost *:8080>
ServerName sitename.ru
ServerAlias www.sitename.ru
DocumentRoot /home/sitename.ru/public_html
</VirtualHost>

Подключим VirtualHost:

# ln -s /etc/apache2/sites-available/sitename.ru.conf /etc/apache2/sites-enabled/

На этом пока Apache оставим в покое. Установите nginx, используя эту статью.

nginx установлен, можно перейти к настройке:

# nano /usr/local/nginx/conf/nginx.conf

В секцию http добавим строчку:

http {

include /etc/nginx/sites-enabled/*;

}

Создадим папку с виртуальными хостами nginx:

# mkdir /etc/nginx/sites-enabled/

Создадим там файл sitename.ru:

# nano /etc/nginx/sites-enabled/sitename.ru

Отконфигурируем как в примере:

#Создайте свой VirtualHost и создайте файл, взяв за пример эти настройки
server {
# какой порт слушать
listen 80;
# доменное имя с www и без
server_name sitename.ru www.sitename.ru;
location / {
# адрес для перенаправления запроса. Т.е. наш Apache
proxy_pass http://localhost:8080/;
# передаём серверу Apache реальный IP юзера
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# типы файлов, обрабатываемые Nginx’ом
location ~* \.(gif|jpg|jpeg|png|ico|css|swf|js|html|htm|xml|txt|gz|bmp|xls)$ {
# директория веб-сервера
root /home/sitename.ru/public_html;
#Включаем mod_rewrite для wordpress
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php;
}
}
}

Устанавливаем memcached:

# aptitude install memcached

Устанавливаем xcache:

# aptitude install php5-xcache

Перезапускаем демоны:

/etc/init.d/apache2 restart

/etc/init.d/nginx restart

/etc/init.d/memcached restart

Готово! Теперь nginx принимает внешние соединение, рулит статикой и проксирует. Apache же занимается динамическим содержимым. Удачи!

Установка nginx из исходников

February 26th, 2012 No comments

День добрый %) Сегодня мы соберем из исходных кодов nginx – самый быстрый http-сервер.

Итак, переходим в папку, в которой будем собирать сырцы:

# cd ~/

Скачиваем nginx (на момент написания этой статьи версия была 1.1.15):

# wget http://www.nginx.org/download/nginx-1.1.15.tar.gz

переходим в папку со скачанным архивом nginx:

# cd nginx-1.1.15

Распаковываем:

# tar -xvf  nginx-1.1.15.tar.gz

Ставим необходимые библиотеки/пакеты, которые необходимы для сборки nginx:

# aptitude install build-essentials libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev

Конфигурируем с параметрами (кстати, описание всех директив с параметрами конфигурации можно найти здесь):

# ./configure –user=www-data –group=www-data –with-http_ssl_module –with-http_realip_module –with-http_addition_module –with-http_sub_module –with-http_dav_module –with-http_flv_module –with-http_gzip_static_module –with-mail  –with-mail_ssl_module

Read more…