- Small. Simple. Secure.
- Alpine Linux is a security-oriented, lightweight Linux distribution based on musl libc and busybox.
- About
- Small
- Simple
- Secure
- Alpine Linux:FAQ
- Contents
- General
- Where to start?
- I have found a bug, where can I report it?
- Are there any details about the releases available?
- How can I contribute?
- Why don’t I have man pages or where is the ‘man’ command?
- What is the difference between edge and stable releases?
- What architectures does Alpine support?
- What kind of release of Alpine Linux are available?
- Setup
- What is the difference between sys, data, and diskless when running setup-alpine or setup-disk ?
- How do I upgrade Alpine?
- My cron jobs don’t run?
- Time and timezones
- How do I set the local timezone?
- Packages
- Can you build an apk package for .
- How can I build my own package?
- What does «required by: world[$pkgname]» mean?
- How can I find out if a certain package exists in Alpine?
- WARNING: Ignoring APKINDEX.xxxx.tar.gz
- Dynamic DNS
- How do I schedule a regular dynamic DNS update?
- Terminal
- How to enable/fix colors for git?
- Old questions, no longer freqently asked
- Alpine freezes during boot from Compact Flash, how can I fix?
- How do I remove the CDROM?
- How can I install a custom firmware in a diskless system?
- How do I play my .ogg/.mp3 files?
- OpenNTPD reports an error with «adjtime»
- Using a cron job to keep the time in sync
- Windows clients reports an error when trying to sync
- Зачем забивать гвозди микроскопом, если есть Alpine Linux?
- Оно нам действительно надо?
- Хочется странного
- Про Alpine
- Приоткроем крышку
- Демоны под крышкой
- А еще
Small. Simple. Secure.
Alpine Linux is a security-oriented, lightweight Linux distribution based on musl libc and busybox.
About
Alpine Linux is an independent, non-commercial, general purpose Linux distribution designed for power users who appreciate security, simplicity and resource efficiency.
Small
Alpine Linux is built around musl libc and busybox. This makes it smaller and more resource efficient than traditional GNU/Linux distributions. A container requires no more than 8 MB and a minimal installation to disk requires around 130 MB of storage. Not only do you get a fully-fledged Linux environment but a large selection of packages from the repository.
Binary packages are thinned out and split, giving you even more control over what you install, which in turn keeps your environment as small and efficient as possible.
Simple
Alpine Linux is a very simple distribution that will try to stay out of your way. It uses its own package manager called apk, the OpenRC init system, script driven set-ups and that’s it! This provides you with a simple, crystal-clear Linux environment without all the noise. You can then add on top of that just the packages you need for your project, so whether it’s building a home PVR, or an iSCSI storage controller, a wafer-thin mail server container, or a rock-solid embedded switch, nothing else will get in the way.
Secure
Alpine Linux was designed with security in mind. All userland binaries are compiled as Position Independent Executables (PIE) with stack smashing protection. These proactive security features prevent exploitation of entire classes of zero-day and other vulnerabilities.
Источник
Alpine Linux:FAQ
This is a list of frequently asked questions about Alpine Linux.
If your question is not answered on this page, use the search box above to find work in progress pages not linked here, or in case of no answer, edit this page and write down your question.
Contents
General
Alpine Linux is used heavily in containers (e.g. docker images) on servers, so many of its main packages are focused on server services.
Where to start?
The «Installation page» provides a basic orientation.
A broader overview may be found on the official «About page», and at the «Wiki Overview».
Please note that testing is safer on your own virtual machine or on a public «DistroTest.net».
I have found a bug, where can I report it?
You can report it in the bugtracker, but search it first to see if the issue has already been reported.
Are there any details about the releases available?
Yes, please check the releases page.
How can I contribute?
You can contribute by:
- Using the software and giving feedback.
- Documenting your Alpine Linux experiences on this wiki.
- In many other ways.
Please visit Contribute page to read more about this topic.
Why don’t I have man pages or where is the ‘man’ command?
The man command and man pages are not installed by default. Many packages have documentation companion packages suffixed -doc. Keep in mind, not all packages have a corresponding documentation package and when there is one it may not include man pages.
To install the man command, and related utilities, first add the man-db package:
Once installed, add documentation for the package where you need it. For example, say you installed nftables and you now require its man pages:
apk add nftables-doc
Now we’ve installed nft(8) and other documentation to our system and you can issue the command:
To always install the documentation companion package, when available, add the docs meta package.
What is the difference between edge and stable releases?
Stable releases are just what they sound like: initially a point-in-time snapshot of the package archives, but then maintained with bug-fixes only in order to keep a stable environment.
Edge is more of a rolling-release, with the latest and greatest packages available in the online repositories.
Occasionally, snapshot ISO images of the then-current state of edge are made and are available for download.
Typically these are made when there are major kernel upgrades or package upgrades that require initramfs rebuilds.
What architectures does Alpine support?
As Alpine uses the Linux kernel, it supports:
- aarch64: The 64-bit only ARM execution state of the ARMv8 device machines.
- armhf: The newer ARM hard-float for newer, more powerful 32-bit devices alongside 64-bit
- armv7: The 32-bit only ARM execution state of the ARMv7 devices machines.
- mips64:
- s390x: For the Super powered IBM mainframes, especially IBM Z and IBM LinuxONE servers.
- ppc64le: For 64-bit PowerPC devices with pure little-endian mode, mostly for POWER8 and POWER9
- x86: (i386, PC 32bit) and x86_64 (i686, PC 64bit and amd64)
- x86_64: The popular AMD64 compatible 64-bit x86 based machines, i386 is not recommended for newer/latest hardware.
Please check Download page for media availability on each one and check Releases pages for latest.
What kind of release of Alpine Linux are available?
Please check the Releases page for more information.
Setup
What is the difference between sys, data, and diskless when running setup-alpine or setup-disk ?
sys: This mode is a traditional disk install. The following partitions will be created on the disk: /boot/, / (filesystem root) and swap. This mode may be used for development boxes, desktops, virtual servers, etc.
data: This mode uses your disk(s) for data storage, not for the operating system. Runs from the media and only a /var/ is created on disk. The system itself will run from a tmpfs (RAM). Use this mode if you only want to use the disk(s) for data, like mailspool, databases, logs, etc.
diskless: No disks are to be used. Alpine local backup may still be used in this mode.
These modes are explained further on the Installation page.
How do I upgrade Alpine?
To upgrade to a new stable release or edge: apk upgrade —available
My cron jobs don’t run?
Start service crond and add it to runlevel:
rc-service crond start && rc-update add crond
After that the cron daemon is started automatically on system boot and executes the scripts placed in the folders under /etc/periodic/ — there’re folders for 15min, hourly, daily, weekly and monthly scripts.
To check whether your scripts are likely to run, use the run-parts command, for example:
run-parts —test /etc/periodic/15min
This command will tell you what should run but will not actually execute the scripts.
If the results of the test are not as expected, check the following:
- Make sure the script is executable — if unsure, issue the command
chmod a+x /etc/periodic/[path/scriptname]
Time and timezones
How do I set the local timezone?
If you wish to edit the timezone (TZ) after installation, run the setup-timezone script.
Packages
Can you build an apk package for .
Yes, we probably can.
Please create an issue in the bugtracker. Prefix with «feat» in title and include a short description (one-line), an URL for the home page, and an URL for the source package.
How can I build my own package?
What does «required by: world[$pkgname]» mean?
It means that the package you try to install does not exist in the repositories you have configured.
Maybe you forgot to add community, testing or unmaintained to /etc/apk/repositories?
Or is the package in a pinned repository and you forgot to suffix the package with the repo tag? Example:
apk add experimental-package@testing
How can I find out if a certain package exists in Alpine?
If you want to only search repositories you have configured in /etc/apk/repositories, then apk search $pkgname should get you sorted. If you want to search all repositories have a look at the online pkg oracle
WARNING: Ignoring APKINDEX.xxxx.tar.gz
If you get WARNING: Ignoring APKINDEX.xxxx.tar.gz: No such file or directory while running package related tools, check your /etc/apk/repositories file.
To check the content of the repositories file
Dynamic DNS
How do I schedule a regular dynamic DNS update?
You’ll want to install the ez-ipupdate package:
apk add ez-ipupdate
After that, create a new file at /etc/ez-ipupdate.conf with contents similar to:
Make the new ip cache directory:
mkdir /var/cache/ez-ipupdate lbu add /var/cache/ez-ipupdate
Then schedule a new cron job with this command:
echo >> /var/log/ez-ipupdate && \
/bin/date >> /var/log/ez-ipupdate && \
ez-ipupdate —config-file /etc/ez-ipupdate.conf -f -F /var/run/ez-ipupdate.pid \
—cache-file /var/cache/ez-ipupdate/ipcache —quiet >> /var/log/ez-ipupdate 2>&1
Don’t forget to backup your settings!
Terminal
How to enable/fix colors for git?
The problem is not in git itself or terminal, but in the less command. Busybox’s less doesn’t support -r (--raw-control-chars) and -R (--RAW-CONTROL-CHARS) options.
The simplest (yet not ideal) solution is to install GNU less:
Old questions, no longer freqently asked
Alpine freezes during boot from Compact Flash, how can I fix?
Most Compact Flash card readers do not support proper DMA.
You should append nodma to the append line in syslinux.cfg .
How do I remove the CDROM?
Since the modloop loopback device is on CDROM you cannot just run eject . You need to unmount the modloop first.
Unmounting both the modloop and the CDROM in one step can be done by executing:
Then it’s possible to eject the CDROM:
How can I install a custom firmware in a diskless system?
The modules and firmware are both special images which are mounted as read-only.
To fix this issue you can copy the firmware directory to your writeable media (cf/usb) and copy your custom firmware to it.
After reboot Alpine should automatically use the directory on your local storage instead of the loopback device.
How do I play my .ogg/.mp3 files?
First, the sound card should be recognized (you must have /dev/snd/***** files)
sox , mpg123 , etc all use the oss sound driver, while Alpine uses ALSA drivers.
So you need to load the snd-pcm-oss compatibility module.
While you’re at it, you might need aumix to turn up the sound volume
echo snd-pcm-oss >> /etc/modules modprobe snd-pcm-oss apk_add aumix sox aumix (set volume settings) play really_cool_song.mp3
OpenNTPD reports an error with «adjtime»
Your log contains something like:
openntpd is supposed to make small adjustments in the time without causing time jumps.
If the adjustment is too big then something is clearly wrong and ntpd gives up. (its actually adjtime(3) that has a limit on how big adjustments are allowed)
You can make ntpd set the time at startup by adding -s option to ntpd. This is done by setting NTPD_OPTS=»-s» in /etc/conf.d/ntpd .
Using a cron job to keep the time in sync
Add the following to /etc/periodic/daily (or use another folder under the /etc/periodic heirarchy if you want to run the script more/less frequently)
Example: file called do-ntp
This queries the uk time server pool — you can modify this to suit your localisation, or just use pool.ntp.org. More info here: http://www.pool.ntp.org/zone/@
Windows clients reports an error when trying to sync
openntpd needs to run for a while before it is satisfied it is in sync. Until then it will set a flag «clock not synchronized» and Windows will report an error while trying to sync with your openntpd server.
Only thing to do is wait, do something else for 15-20mins and then check.
Источник
Зачем забивать гвозди микроскопом, если есть Alpine Linux?
По зову сердца и работе в Digital Design в качестве системного инженера, мне часто приходится сталкиваться с переусложненными программными продуктами и архитектурными конструкциями. Это вызывает страстное желание минимизации и упрощения всего, что попадается под руку, и приводит к восторгу от человеческих решений, просто делающих свою работу , без регистрации и смс .
Так я и познакомился с Alpine Linux.
Этот дистрибутив может вам понравиться по следующим причинам:
- Если вы любите минимализм и инструменты, ориентированные на выполнение поставленной задачи без лишних свистелок и украшений;
- Если вы заметили, что имеющиеся «мэйнстримные» дистрибутивы немного (?) раздуты и избыточны;
- Если вы захотели решить имеющуюся задачу простым способом.
Под «мэйнстримом» я подразумеваю тройку CentOS — Debian — Ubuntu (конечно же, ими мир не заканчивается), да простят меня все верующие в эти замечательные дистрибутивы. При их использовании, периодически, на границе восприятия, возникает колкая мысль – «а может быть можно проще?».
Оно нам действительно надо?
$ holywar mode disable
Неужели для решения вашей небольшой задачи требуется все это:
Замечательная systemd. Система инициализации (уже не совсем), которая может произвести впечатление системы управления шаттлом?
Подсистема журналирования / аудита, построенная на связке вроде journald → rsyslogd + auditd?
Можно догадываться, почему это сделано именно так, но действительно ли для моей простой задачи требуется такая цепочка?
Дублирование функциональности периодического выполнения задач как в systemd, так и в crond?
Сосуществование нескольких подсистем управления сетью в разных сочетаниях: классический networking / networkd / NetworkManager?
Сервисы вида tuned и firewalld?
Локальный почтовый сервис. Вы точно будете его использовать?
Раз уж мы вспомнили про минимализм, можно очень грубо сравнить наши дистрибутивы-лидеры в их минимальном варианте установки:
- Лидером избыточности по дисковому пространству и числу пакетов оказывается Ubuntu 18.04 (2,8 ГБ дискового пространства, 342 пакета, 31 активный сервис systemd, 15 процессов при входе). Семейство systemd тут представлено в максимальном объеме — systemd, networkd, timesyncd, resolved, logind, есть dbus.
- CentOS 7.5.1804 проигрывает по диску и числу пакетов, но лидер по вероятно-избыточным сервисам (1.1 ГБ дискового пространства, 299 пакетов, 34 активных сервиса systemd, 19 процессов при входе, среди которых — NetworkManager, firewalld, tuned, postfix, polkitd, auditd, journald + rsyslogd, dbus).
- Debian 9.4.0 пытались сильно не надувать: 940 МБ, 334 пакета, 25 активных сервисов systemd, 14 процессов при входе. Само собой, тут тоже есть systemd (а также journald, timesyncd и сопутствующий dbus), но без особого фанатизма в части управления сетью.
holywar: cannot change mode to ‘disable’: Permission denied
Хочется странного
От части перечисленного выше можно (попробовать) избавиться вручную, но вдруг все уже придумано за нас? В идеале, от дистрибутива серверной операционной системы общего назначения хочется видеть:
- Как ни странно, загрузчик, который дотянет нас до ядра;
- Само ядро ОС (в рассматриваемом случае — linux);
- Система инициализации, которую ядро запустит по готовности. Желательно, по простоте недалеко ушедшая от топора;
- Минимальный набор процессов, который запустит система инициализации. Ну например:
- Окончательная инициализация устройств и определение дополнительных параметров ядра;
- Обеспечение журналирования (можно с текстовыми журналами? Ну пожалуйста);
- Конфигурация сети (хорошо бы, с меньшим числом управляющих прослоек);
- Синхронизация времени (ntpd / chronyd);
- Несколько локальных консолей;
- Опционально — периодическое выполнение задач (сrond);
- Опционально — удаленный доступ к системе (sshd);
- Хорошо бы еще сохранять и восстанавливать конфигурацию межсетевого экрана.
И на этом почти все, остальное — дело менеджера пакетов. Меньше исполняемого кода и конфигурации – меньше багов, меньше багов – меньше багов. А система все также запущена и доступна по сети. Идея выглядит неплохо, теперь посмотрим, насколько близок к ней дистрибутив Alpine Linux.
Про Alpine
Чем может очаровать Alpine, особенно после CentOS? Отчаянным минимализмом!
Ну и, конечно, отсутствием необходимости сертификации «Linux Systemd Certified Voldemort».
Что сделали авторы:
- Понизили число используемых базовых компонентов;
- Выбрали модули поменьше и попрозрачнее;
- Упростили процесс конфигурирования системы.
- Чрезвычайно лаконичный процесс установки с использованием консольной утилиты setup-alpine;
- В качестве загрузчика взят extlinux из состава проекта syslinux;
- Небольшой инструмент сборки mkinitfs для создания временной файловой системы, используемой при загрузке;
- Система инициализации openrc с определением зависимостей между сервисами, уровнями запуска и щепоткой скриптования;
- Замена стандартной библиотеки GNU libc на более легковесную musl libc;
- Вместо пакета GNU coreutils большинство стандартных системных утилит в несколько урезанном исполнении входят в состав пакета busybox, который может быть Вам знаком по встраиваемым решениям;
- По умолчанию используется командный интерпретатор ash в составе busybox. Само собой, никто не мешает при необходимости поставить bash , ну и systemd ;
- Собственный пакетный менеджер apk и собственная инфраструктура распространения пакетов.
Кроме того, авторы реализовали ряд мер, ориентированных на повышение уровня защищенности базовой системы:
- Применили патчи ядра grsecurity/PaX (про их эффективность мнения расходятся, но все же); Уже нет, спасибо коллеге из комментариев. Как раз 26 июня вышла версия 3.8.0.
- Собрали пакеты с использованием режимов, снижающих вероятность эксплуатации ряда возможных уязвимостей.
В итоге мы получаем систему, снабженную рядом дополнительных механизмов защиты, позволяющую решить имеющуюся задачу и занимающую около 130 МБ. В запущенной системе установлен 41 пакет и выполняется 13 пользовательских процессов, можно стучаться по ssh.
И больше ничего. Осталось добавить то, что нужно вам (да и iptables с возможностью восстановления конфигурации при старте поставьте).
Приоткроем крышку
Обратите внимание – Alpine может пригодиться как учебная площадка при ознакомлении с ОС Linux! Увидеть логику работы компонентов субъективно проще, чем пытаться охватить сходу CentOS или Ubuntu:
- Загрузчик нашей установленной системы прост, его конфигурация влезает в 12 строк:
- Да и в /boot не слишком многолюдно:
- А вот и запущенный загрузчик без модных обоев:
- Ядро загружается, подхватывает initramfs, отрабатывает собственные шаги инициализации и вызывает команду init (которая, на самом деле, тоже идет в составе busybox). Init использует файл /etc/inittab:
- И тут в явном виде прописано, что нужно запустить для инициализации системы:
- Запустить 6 процессов getty, ожидающих на 6 виртуальных консолях локального входа пользователя.
- Запустить систему инициализации openrc для поочередного достижения требуемых уровней инициализации (openrc использует не классические уровни инициализации 0-6, а собственные уровни/группы sysinit — boot — default).
Далее состояние системы зависит от конфигурации openrc, а именно:
- Переменных, заданных в файлах каталога /etc/conf.d;
- Скриптов запуска, находящихся в каталоге /etc/init.d;
- Привязки скриптов запуска к «группам инициализации»:
Осталось прочитать скрипты запуска и обработать их с учетом уровней запуска и зависимостей.
Можем на примере syslog (/etc/init.d/syslog) посмотреть, как выглядит скрипт запуска openrc.
Как видите, это не всегда эти ваши нелюбимые «портянки»:
Переменные, используемые при выполнении скрипта, определяются в соответствующем файле /etc/conf.d/syslog. В нашем случае, в файле определена переменная SYSLOGD_OPTS=»-Z».
Обратите внимание — в скрипте декларативно определены зависимости данного сервиса.
Openrc честно перебирает в заданном порядке скрипты запуска, достигает уровня «default» — и вот она, рабочая система!
Демоны под крышкой
Что же именно скрывается под скриптами запуска openrc? Как ни странно — набор задач и демонов, перечисленных ниже.
Сначала, на уровне sysinit:
- dmesg — выставляется уровень журналирования для сообщений от ядра;
- devfs — монтируется и настраивается /dev;
- mdev — запускается менеджер устройств;
- hwdrivers — загружаются модули устройств на основе информации из /sys и /dev;
Следующим идет уровень boot:
- modules — загружаются модули ядра, перечень которых определен в /etc/modules;
- hwclock — настраиваются аппаратные часы реального времени;
- sysctl — задаются параметры ядра, определенные нами в /etc/sysctl.conf;
- swap — подключается swap-раздел;
- bootmisc — очищаются временные каталоги;
- urandom — настраивается генератор случайных чисел;
- keymaps — инициализируется раскладка клавиатуры;
- hostname — задается имя машины, которое определено в /etc/hostname;
- networking — поиск и инициализация интерфейсов с использованием информации из /etc/network/interfaces;
- syslog — запускается демон журналирования из состава busybox;
И наконец, уровень default:
- chrony — запускается NTP-сервис;
- crond — запускается сервис выполнения задач по расписанию;
- acpid — запускается сервис отслеживания событий питания;
- sshd — запускается сервис удаленного доступа.
Ура, после выполнения этих шагов система готова к работе! Не забудем и про зависимости от перечисленных выше сервисов, которые были заданы в init.d файлах:
- sysfs — монтирование /sys;
- fsck — проверка и исправление файловых систем;
- root — монтирование корневой системы на запись/чтение;
- localmount — монтирование всех файловых систем, перечисленных в /etc/fstab;
- klogd — журналирование событий ядра.
Открываем одну из локальных консолей, где нас поджидает getty, вводим логин, после чего передаем пароль процессу login и получаем доступ к запущенному командному интерпретатору ash (при запуске которого выполняется содержимое файлов /etc/profile, /etc/profile.d/* и
/.profile для подготовки пользовательского окружения).
Ура, никаких дополнительных сущностей (несомненно, полезных в ряде случаев, вроде PAM) — а мы в системе!
Осталось воспользоваться пакетным менеджером apk, и поискать нужные нам для нашей задачи пакеты. (Есть ли они там? Можно оценить это через веб-портал).
А еще
Дистрибутив Alpine не идеален, но его лаконичность меня действительно впечатлила, особенно в роли контейнера (всего 6 процессов — init, 4*getty, syslogd). Для меня он выглядит так, как должна выглядеть минимальная серверная операционная система (прости меня, CentOS!).
Кроме того, он вполне подходит на роль учебной площадки, позволяющей увидеть, из чего состоит современный дистрибутив, не погружаясь сразу в пучину whateverd-сервисов и многократного дублирования функциональности в великолепно-многоуровнево-конфигурируемых-средствах на все случаи жизни.
Источник