Hosting a Web Site on a Raspberry Pi — My HydroPi

Hosting a Web Site on a Raspberry Pi - My HydroPi Хостинг

Introduction

Various web servers can be related to the Raspberry Pi, and each has utilization advantages. This tutorial uses the Apache webserver application.

«хостинг» на чужих серверах

Если кто-то рискнёт открыть порты на своём компьютере и посмотрит в логи — то сразу поймёт, в какую враждебную среду он попал. Множество попыток сканирования по всем стандартным портам с запросами на установленное ПО. Если не принимать защитных мер, то в софте практически на любом сервере можно найти уязвимости — и получить к нему доступ с правами администратора.

Дальше злоумышленник уже сам выбирает, что делать с ресурсами, которые попали к нему в руки: сделать дефейс ради лулзов, установить майнер криптовалюты, добавить в ботнет для DDoS’а или разместить файлы для распространения. Это и называется «хостинг на чужих серверах» — незаконная опция, которой пользуются злоумышленники.

Например, самый крупный современный ботнет Emotet распространяет свою вредоносную нагрузку через сеть взломанных сайтов, которые бот-мастер с условным именем именем Иван контролирует через свои веб-шеллы, установленные там.

Так же работают некоторые другие ботнеты. В их состав которых входят домашние компьютеры, веб-серверы под Linux, смартфоны, маршрутизаторы и другие устройства интернета вещей, например, умные телевизоры под Android.

На устройствах из ботнета злоумышленник может размещать свои файлы как на своеобразном распределённом хостинге. Это довольно надёжное хранилище, потому что многие пользователи годами не обновляют софт, не используют файрвол и не следят за трафиком.

Moving up to nginx

The Nginx web server can be installed on a Debian-based system with one command:

%sudoapt-get install nginx

Prerequisites

For the readers to follow through, they are assumed to have an installed operating system with the Pixel window manager. In summary, you need to have:

  1. A Raspberry Pi Zero W.
  2. Apache webserver.
  3. Internet.
  4. Modules such as SSH enabled.

Setting up the database

On a Debian-based system, you can install SQLite the usual way (with % representing the command-line prompt):

%sudoapt-get install sqlite3

This database system is a collection of C libraries and utilities, all of which come to about 500KB in size. There is no database server to start, stop, or otherwise maintain.

Читайте также:  Как это работает: Пара слов о DNS / Хабр

Once SQLite is installed, create a database at the command-line prompt:

% sqlite3 snowfall.db

If this succeeds, the command creates the file snowfall.db in the current working directory. The database name is arbitrary (e.g., no extension is required), and the command opens the SQLite client utility with >sqlite as the prompt:

Enter ".help"for usage hints.
sqlite>

Create the snowfall table in the snowfall database with the following command. The table name, like the database name, is arbitrary:

sqlite> CREATE TABLE snowfall (id INTEGER PRIMARY KEY AUTOINCREMENT,
region TEXT NOT NULL,
device TEXT NOT NULL,
amount DECIMAL NOT NULL,
tstamp DECIMAL NOT NULL);

Step 1: accessing the terminal

This step will describe how to access the raspberry pi’s terminal. This can be achieved in two main ways as shown below:

  1. You can access the command terminal by clicking CLRL ALT T from the Raspbian desktop.

Step 2: updating packages

In this step, we will make sure that the available packages in our Raspberry pi are updated by typing the command below into the terminal. This ensures you have the current versions of any file you download afterward.

Step 3: installing apache

In the third stage, we will install apache. To Install apache2, we run the following command:

Step 5: downloading mysql

After PHP has been successfully installed, we can now download our desired database. In this tutorial we are using the MySQL database.
To download MySQL, run the following command in the terminal:

Note: When prompted to change the root password, please choose a strong password for MySQL. Make sure to write it down somewhere you can refer to later on.

Step 7: restarting the server

At this point, we will restart the webserver, apache2, to confirm that the changes take effect and are running. Use the command:

Читайте также:  Будьте впереди благодаря точному управлению запасами компьютерного оборудования

The snowfall application

Imagine a downhill ski area large enough to have microclimates, which can mean dramatically different snowfalls across the area. The area is divided into regions, each of which has devices that record snowfall in centimeters; the recorded information then guides decisions on snowmaking, grooming, and other maintenance operations.

This snowfall application uses the following technologies:

Python includes a software driver for communicating with SQLite. There are options for connecting Python scripts with Nginx and other web servers. One option is uWSGI (Web Server Gateway Interface), which updates the ancient CGI (Common Gateway Interface) from the 1990s.

Several factors speak for uWSGI:

  • uWSGI is flexible. It can be used as either a lightweight concurrent web server or the backend application server connected to a web server such as Nginx.
  • Its setup is minimal.
  • The snowfall application involves a low to moderate volume of hits on the web server and database system. In general, CGI technologies are not fast by modern standards, but CGI performs well enough for department-level web applications such as this one.

Various acronyms describe the uWSGI option. Here’s a sketch of the three principal ones:

For convenience, I will use «uwsgi» as shorthand for the binary protocol, the application server, and the very lightweight web server.

The snowfall application code

Below is the source code file requestHandler.py for the snowfall application. (It’s also available on my website.) Different functions within this code help clarify the software architecture that connects SQLite, Nginx, and uwsgi.

Wrapping up

The snowfall application shows how free software components—a high-powered web server, an ACID-compliant database system, and scripting for dynamic content—can support a realistic web application on a Raspberry Pi 4 platform. This lightweight machine lifts above its weight class, and Debian eases the lifting.

The software components in the web application work well together and require very little configuration. For higher volume hits against a relational database, recall that a free and feature-rich alternative to SQLite is PostgreSQL. If you’re eager to play on the Raspberry Pi 4—in particular, to explore server-side web programming on this platform—then Nginx, SQLite or PostgreSQL, uwsgi, and Python are worth considering.

Читайте также:  Russia War Crimes

Блокчейн и распределённый хостинг

На базе блокчейна создан ряд экспериментальных проектов, в том числе криптовалюты, умные контракты, проверка подлинности документов, электронное голосование и многое другое, в том числе и децентрализованный хостинг. Одним из первых проектов такого рода стал Swarm от разработчика Ethereum Виктора Трона.

Welcome to the Swarm.... Bzzz Bzzzz Bzzzz
 /
 o ^ o /
 ( ) /
____________(%%%%%%%)____________
( / / )%%%%%%%(   )
(___/___/__/ ________)
( / /(%%%%%%%)  )
(__/___/ (%%%%%%%) _____)
/( )
/ (%%%%%) 
(%%%)
!

Децентрализованный хостинг предполагает, что сайт одновременно хранится сразу у нескольких участников сети. Теоретически, это повышает устойчивость сайта против DDoS-атак или государственной цензуры.

Веб-сервер на домашнем компьютере

Hosting a Web Site on a Raspberry Pi - My HydroPi
Домашний сервер в винтажном корпусе, источник

Старому компьютеру всегда можно найти применение: он может работать как торрент-клиент и медиасервер (раздавая видео через Plex на все телевизоры, ноутбуки и смартфоны), как файловое хранилище, архив бэкапов, а также как веб-сервер. Нет ничего проще.

Конечно, для стандартного программного стека лучше установить Linux, но и в Windows нет ничего зазорного. По крайней мере, 29,2% серверов в интернете работает под Windows, так что не обязательно менять операционную систему, если на компьютере изначально стояла она, тем более если вам привычно работать с такими инструментами, как ASP.NET и C.

Для простоты можно сразу установить весь комплект программ. Выбираем один из стеков AMP (Apache, MySQL/MariaDB, Perl/PHP/Python) под любую платформу: Windows, macOS, Linux, BSD. Например, комплект WampServer под Windows.

Хостинг на raspberry pi

Алгоритм понятен: нужно поднять веб-сервер на Raspberry Pi и подключить его к сети. Это не какая-то экзотика, а вполне штатное использование «малинки». На официальном сайте даже есть инструкции по установке Apache и Nginx.

Как вариант, веб-сервер можно поднять прямо на маршрутизаторе (с прошивкой OpenWRT).

Conclusion

Web hosting offered by providers of such services is given at a price and in some cases, it can be very expensive. Hence, it is important to find ways of cutting such costs, especially if the hosted service is only for a small group of people.

By following the steps presented above, it is possible to install and host a web server using a Raspberry Pi. The hosted web server can be used to serve a small office through an intranet and is more cost-efficient.

Оцените статью
Хостинги