Today we will configure a web server on our Raspberry Pi mini server or its analogue. The advantages of such a solution are low electricity consumption, silent operation since all cooling is passive, by the way, if there is an uninterruptible power source, then the router and this mini server can hang on the uninterrupted device for a long time in case of an emergency power outage. Of the disadvantages, only insufficient power for high-load sites, stores, that is, those whose interruption will be noticeable for business. Small sites, business cards, this server will pull only so, of course, no DDoS attack will not withstand, but when they take up DDoS and with good money, almost no one can withstand it.
Add a repository to install the necessary packages:
For Debian 7 Wheezy:
deb http://archive.raspbian.org/raspbian wheezy main contrib non-free deb-src http://archive.raspbian.org/raspbian wheezy main contrib non-free deb http://mirrordirector.raspbian.org/raspbian/ wheezy main contrib non-free rpi
For Debian 8 Jessie:
deb http://archive.raspbian.org/raspbian jessie main contrib non-free deb-src http://archive.raspbian.org/raspbian jessie main contrib non-free deb http://mirrordirector.raspbian.org/raspbian/ jessie main contrib non-free rpi
Add the repository keys to the system:
wget -O /tmp/raspbian.public1.key http://archive.raspbian.org/raspbian.public.key && apt-key add /tmp/raspbian.public1.key wget -O /tmp/raspbian.public2.key http://mirrordirector.raspbian.org/raspbian.public.key && apt-key add /tmp/raspbian.public2.key
There are some features of installing the PHP version of the language that you need to consider when installing an operating system to run your site on a Raspberry Pi mini server:
-
Debian 7 Wheezy is the default version of PHP 5.4.
-
Debian 8 Jessie is the default version of PHP 5.6.
At my disposal Raspberry Pi server with the following parameters: 1Gb System Flash, 512Mb RAM and 8Gb Flash we will divide into 3 sections: /var - 1Gb, /usr - 1Gb, /home - all the remaining space and transfer these sections from the system flash drive. Operating system on a mini server Debian 7 Wheezy or Debian 8 Jessie, which we installed earlier according to the instructions Install Debian on a Raspberry Pi mini serverAs well as a 1A power supply from an old mobile phone.
! If the system flash drive has a partition of more than 4 Gb, it is possible to transfer partitions without getting dirty, since for the server the system USB drive in 4Gb and above is enough.
! Attention. I strongly recommend using a Raspberry Pi flash drive to install systems other than Transcend, as when installed on Transcend, the system after restarting or updating can beat the file system and does not load. Kingston and Apacer did not have this problem. This problem was with two Raspberry Pi boards with multiple Transcend cards of different sizes and classes.
Since the hardware is not super powerful, we will install a lightweight web server Nginx, PHP-FPM, APC and MYSQL database server with phpmyadmin.
Install the necessary packages of programs:
apt-get install exim4 ntp ntpdate apache2-utils nginx php5-fpm php-apc php5-curl mysql-client mysql-server php5-mysql phpmyadmin sudo
Agree to all questions of the installer by pressing the letter y. When installing a mysql database, the installer will prompt you to enter and repeat the user’s root database password, be sure to write it in a safe place, for example in a notebook, so that you do not have to restore it.
Install the 8gb flash drive on which the files and logs of the website will be located
Connect the 8GB flash drive to the USB port of the mini server and check whether the flash drive is visible in the system by executing the command:
fdisk -l
Sitima's answer:
Disk /dev/mmcblk0: 1023 MB, 1023934464 bytes
4 heads, 16 sectors/track, 31248 cylinders, total 1999872 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/mmcblk0p1 8192 122879 57344 6 FAT16
/dev/mmcblk0p2 122880 1999871 938496 83 Linux
Disk /dev/sdb: 7948 MB, 7948206080 bytes
255 heads, 63 sectors/track, 966 cylinders, total 15523840 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000f1f67
Device Boot Start End Blocks Id System
/dev/sdb1 63 15518789 7759363+ b W95 FAT32So here we see that the system sees a flash drive. /dev/sdbsize 7948 MB(8Gb), as well as that the flash drive is formatted in the Windows Fat32 file system.
Let’s start splitting the flash drive by following the command:
fdisk /dev/sdb
To view the parameters of the fdisk program, you need to type a letter. mThe program will provide a list of possible commands:
Command (m for help): m Command action a toggle a bootable flag b edit bsd disklabel c toggle the dos compatibility flag d delete a partition l list known partition types m print this menu n add a new partition o create a new empty DOS partition table p print the partition table q quit without saving changes s create a new empty Sun disklabel t change a partition's system id u change display/entry units v verify the partition table w write table to disk and exit x extra functionality (experts only)
Check the partition table on the flash drive by clicking p:
Command (m for help): p Disk /dev/sdb: 7948 MB, 7948206080 bytes 255 heads, 63 sectors/track, 966 cylinders, total 15523840 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x000f1f67 Device Boot Start End Blocks Id System /dev/sdb1 63 15518789 7759363+ b W95 FAT32
Delete the existing section on the flash drive by pressing the letter d:
Command (m for help): d Selected partition 1
Check that the section is deleted by typing a letter p:
Command (m for help): p Disk /dev/sdb: 7948 MB, 7948206080 bytes 255 heads, 63 sectors/track, 966 cylinders, total 15523840 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x000f1f67 Device Boot Start End Blocks Id System
Create a section. /usr 1Gb by typing a letter n:
Command (m for help): n
Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p):
Using default response p
Partition number (1-4, default 1):
Using default value 1
First sector (2048-15523839, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-15523839, default 15523839): +1GCreate a section. /var 1Gb by typing a letter n:
Command (m for help): n
Partition type:
p primary (1 primary, 0 extended, 3 free)
e extended
Select (default p):
Using default response p
Partition number (1-4, default 2):
Using default value 2
First sector (2099200-15523839, default 2099200):
Using default value 2099200
Last sector, +sectors or +size{K,M,G} (2099200-15523839, default 15523839): +1GCreate a section. /home the size of the remaining place by typing a letter n:
Command (m for help): n
Partition type:
p primary (2 primary, 0 extended, 2 free)
e extended
Select (default p):
Using default response p
Partition number (1-4, default 3):
Using default value 3
First sector (4196352-15523839, default 4196352):
Using default value 4196352
Last sector, +sectors or +size{K,M,G} (4196352-15523839, default 15523839):
Using default value 15523839Check the created sections by typing a letter p:
Command (m for help): p Disk /dev/sdb: 7948 MB, 7948206080 bytes 255 heads, 63 sectors/track, 966 cylinders, total 15523840 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x000f1f67 Device Boot Start End Blocks Id System /dev/sdb1 2048 2099199 1048576 83 Linux /dev/sdb2 2099200 4196351 1048576 83 Linux /dev/sdb3 4196352 15523839 5663744 83 Linux
Write down the changes made to the flash drive by typing a letter w:
Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks.
Check the breakdown of the flash drive by following the command:
fdisk -l ... Disk /dev/sdb: 7948 MB, 7948206080 bytes 245 heads, 62 sectors/track, 1021 cylinders, total 15523840 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x000f1f67 Device Boot Start End Blocks Id System /dev/sdb1 2048 2099199 1048576 83 Linux /dev/sdb2 2099200 4196351 1048576 83 Linux /dev/sdb3 4196352 15523839 5663744 83 Linux
We begin to format the created sections by executing commands:
mkfs.ext4 /dev/sdb1 mkfs.ext4 /dev/sdb2 mkfs.ext4 /dev/sdb3
Mount the first partition into a folder /mntCopy the contents of the section /usr And we'll unmount the section by executing commands:
mount /dev/sdb1 /mnt/ cp -Rp /usr/* /mnt/ umount /mnt
Mount the second partition into a folder /mntCopy the contents of the section /var And we'll unmount the section by executing commands:
mount /dev/sdb2 /mnt/ cp -Rp /var/* /mnt/ umount /mnt
Mount the third partition into a folder /mntCopy the contents of the section /home And we'll unmount the section by executing commands:
mount /dev/sdb3 /mnt/ cp -Rp /home/* /mnt/ umount /mnt
Changes to the partition mount file /etc/fstab
vi /etc/fstab ... /dev/sdb1 /usr ext4 defaults,noatime 0 2 /dev/sdb2 /var ext4 defaults,noatime 0 2 /dev/sdb3 /home ext4 defaults,noatime 0 2 # монтирум папку логов в оперативную память для дольшей работы флешки: tmpfs /var/log tmpfs rw,size=150m 0 0
Since the system flash drive is small, and system partitions /usr and /var we copied to a separate flash drive, fstab configured, then the files from the system USB drive are deleted and rebooted by executing the commands:
rm -rf /usr/* rm -rf /var/* reboot
After the reboot, the board will be loaded from two flash drives. Be sure to make images of both flash drives after the setting is completed, so that you do not have to configure everything again when any flash drive fails.
Configure PHP
Changes to the PHP configuration file:
vi /etc/php5/fpm/php.ini
was:
... ;cgi.fix_pathinfo=1 ... ;date.timezone = ...
became:
... cgi.fix_pathinfo=0 ... date.timezone="Europe/Kiev" ...
Configure APC to caching php scripts:
vi /etc/php5/fpm/conf.d/20-apc.ini extension=apc.so ; Включаем APC: apc.enabled=1 ; Количество сегментов памяти: apc.shm_segments=1 ; Размер одного сегмента памяти": apc.shm_size=64
Customize Nginx
We configure a web server, add a domain on which the site will work on our board, for example, the site will be called webserver.loc
Add a group to which we will add the user under which the web server will work by executing the command:
addgroup --gid 10000 webserver
Add a user from the home directory /home/www/webserver.loc And then I did the command.
adduser --home /home/www/webserver.loc --shell /dev/null --uid 10000 --gid 10000 --disabled-password --disabled-login --gecos '' webserver
We create a directory structure of the website:
mkdir /home/www/webserver.loc/logs mkdir /home/www/webserver.loc/www mkdir /home/www/webserver.loc/tmp mkdir /home/www/webserver.loc/sessions chown -R webserver:webserver /home/www/webserver.loc/
Create a configuration file webserver.loc.conf folder pool.d domain-created webserver.loc and make changes to this file:
vi /etc/php5/fpm/pool.d/webserver.loc.conf [webserver.loc] user = webserver group = webserver listen = 127.0.0.1:9000 listen.owner = webserver listen.group = webserver listen.mode = 0660 pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 chdir = / php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f [email protected] php_flag[display_errors] = off php_admin_value[error_log] = /home/www/webserver.loc/logs/fpm-php.www.log php_admin_flag[log_errors] = on php_admin_value[upload_tmp_dir] = /home/www/webserver.loc/tmp php_admin_value[session.save_path] = /home/www/webserver.loc/sessions php_admin_value[open_basedir] = /home/www/webserver.loc/www:/home/www/webserver.loc/tmp:/home/www/webserver.loc/sessions:/usr/share/phpmyadmin php_admin_value[mail.log] = /home/www/webserver.loc/logs/mail.log php_admin_value[memory_limit] = 128M php_admin_value[post_max_size] = 18M php_admin_value[max_execution_time] = 300 php_admin_value[allow_url_fopen] = Off php_admin_value[upload_max_filesize] = 18M php_admin_value[date.timezone] = Europe/Kiev
Turn off the default settings for the web server by following the command:
unlink /etc/nginx/sites-enabled/default
Create a Nginx web server configuration file for our webserver.loc domain:
vi /etc/nginx/sites-available/webserver.loc.conf
# redirect www
server {
listen 80;
server_name www.webserver.loc;
return 301 $scheme://webserver.loc$request_uri;
}
server {
listen 80; ## listen for ipv4
# root dir of your pages
root /home/www/webserver.loc/www/;
index index.php index.html index.htm;
server_name webserver.loc;
location / {
try_files $uri $uri/ /index.html;
}
# pass the PHP scripts to FastCGI
location ~ \.php$ {
try_files $uri = 404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# php5-fpm :
fastcgi_pass 127.0.0.1:9000;
fastcgi_read_timeout 300;
fastcgi_index index.php;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root concurs with nginx's one
location ~ /\.ht {
deny all;
}
# error and access logs
# error_log /home/www/webserver.loc/logs/nginx-error.log crit;
error_log /home/www/webserver.loc/logs/nginx-error.log;
access_log /home/www/webserver.loc/logs/nginx-access.log;
#Работа с phpMyAdmin
location /phpmyadmin {
root /usr/share/;
index index.php index.html index.htm;
location ~ ^/phpmyadmin/(.+\.php)$ {
try_files $uri =404;
root /usr/share/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_read_timeout 300;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $request_filename;
include /etc/nginx/fastcgi_params;
}
location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
root /usr/share/;
}
}
location /phpMyAdmin {
rewrite ^/* /phpmyadmin last;
}
}File in. /etc/nginx/nginx.conf enter the data:
vi /etc/nginx/nginx.conf
user www-data;
# Число рабочих процессов nginx, рекомендуется ставить по количеству процессоров/ядер на вашем сервере
worker_processes 1;
# Уменьшает число системных вызовов gettimeofday(), что приводит к увеличению производительности
timer_resolution 100ms;
# Изменяет ограничение на число используемых файлов RLIMIT_NOFILE для рабочего процесса.
worker_rlimit_nofile 8192;
# Директива задаёт приоритет рабочих процессов от -20 до 20 (отрицательное число означает более высокий приоритет).
worker_priority -20;
# Путь к логу ошибок
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 768;
use epoll;
# multi_accept on;
}
http {
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
# log options
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio" "$request_time"';
access_log /var/log/nginx/access.log main;
# Включить sendfile(). Использование sendfile() экономит системные вызовы, уменьшает число копирований данных, позволяет использовать меньше физической памяти.
sendfile on;
# Разрешаем использовать TCP_CORK в Linux, что позволяет передавать заголовок ответа и начало файла в одном пакете в Linux
tcp_nopush on;
# Задаём таймаут, в течение которого keep-alive соединение с клиентом не будет закрыто со стороны сервера. Второй параметр задаёт значение в строке "Keep-Alive: timeout=время" в заголовке ответа.
#keepalive_timeout 0;
keepalive_timeout 35 45;
# Разрешаем использовать опцию TCP_NODELAY
tcp_nodelay on;
# Запрещаем выдавать версию nginx'а в сообщениях об ошибках и в строке заголовка ответа "Server".
server_tokens off;
# Разрешаем сжатие ответа методом gzip.
gzip on;
#Разрешаем проверку готового сжатого файла.
gzip_static on;
# Устанавливаем уровень сжатия ответа методом gzip.
gzip_comp_level 4;
# Устанавливаем минимальную длину ответа, для которых будет выполняться сжатие ответа методом gzip
gzip_min_length 1024;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_buffers 64 8k;
gzip_http_version 1.1;
gzip_proxied any;
gzip_types
text/plain
text/css
text/x-js
text/xml
text/javascript
application/javascript
application/x-javascript
application/json
aplication/xml
application/xml+rss
application/vnd.ms-fontobject
application/x-font-ttf
font/ttf
font/opentype;
proxy_connect_timeout 600 ;
proxy_send_timeout 600 ;
proxy_read_timeout 600 ;
send_timeout 600 ;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Attention!! If the restart of the web server gives an error:
Restarting nginx: nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32 nginx: configuration file /etc/nginx/nginx.conf test failed
It is necessary to add a parameter to the http section server_names_hash_bucket_size:
http {
server_names_hash_bucket_size 64;
...To check the work of PHP scripts on the server, create a file in the site directory index.php with the contents:
<?php phpinfo(); ?>
You can create the same file by executing the command:
echo '<?php phpinfo(); ?>' > /home/www/webserver.loc/www/index.php
Enable the domain by creating a symbolic link and restart Nginx and php5-fpm by executing the commands:
ln -s /etc/nginx/sites-available/webserver.loc.conf /etc/nginx/sites-enabled/ /etc/init.d/nginx restart /etc/init.d/php5-fpm restart
After that, we can open your domain address in the browser. webserver.loc And look at the page that opens with PHP parameters.
Attention!! If you have a Debian Jessie operating system installed and opens a white screen instead of a page with information about PHP, you need to make changes to the file. /etc/nginx/fastcgi_params:
vi /etc/nginx/fastcgi_params fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; ...
Overload Nginx WEB server by executing the command:
/etc/init.d/nginx restart
If you need to open phpmyadmin to work with Mysql, we open the browser address and enter the root login and password that you entered during the installation of mysql server:
http://webserver.loc/phpmyadmin/
Today, we have installed a web and database server on a single board computer Raspberry Pi or its analogue (for example, Orange Pi) sufficient for the operation of a small website, telephone PBX.
I was with you. Sergey Lazarenko.
Let’s take a short break and watch a video of how to make a bath in the camp:



comment