Установка alpine linux: подробная инструкция для пользователей

Save Firewall Rules

For ip6tables

  1. Set ip6tables to start on reboot
  2. Write the firewall rules to disk
  3. If you use Alpine Local Backup:
    1. Save the configuration

Activating Changes and Testing Connectivity

Changes made to can be activated by running:

/etc/init.d/networking restart

If you did not get any errors, you can now test that networking is configured properly by attempting to ping out:

ping www.google.com

PING www.l.google.com ( 56(84) bytes of data.
64 bytes from yw-in-f103.1e100.net ( icmp_seq=1 ttl=48 time=58.5 ms
64 bytes from yw-in-f103.1e100.net ( icmp_seq=2 ttl=48 time=56.4 ms
64 bytes from yw-in-f103.1e100.net ( icmp_seq=3 ttl=48 time=57.0 ms
64 bytes from yw-in-f103.1e100.net ( icmp_seq=4 ttl=48 time=60.2 ms
--- www.l.google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3007ms
rtt min/avg/max/mdev = 56.411/58.069/60.256/1.501 ms

For an IPv6 traceroute (), you will first need to install the package:

apk add iputils

Then run :

traceroute6 ipv6.google.com

traceroute to ipv6.l.google.com (2001:4860:8009::67) from 2001:470:ffff:ff::2, 30 hops max, 16 byte packets
 1  2001:470:ffff:ff::1 (2001:470:ffff:ff::1)  3.49 ms  0.62 ms  0.607 ms
 2  *  *  *
 3  *  *  *
 4  pr61.iad07.net.google.com (2001:504:0:2:0:1:5169:1)  134.313 ms  95.342 ms  88.425 ms
 5  2001:4860::1:0:9ff (2001:4860::1:0:9ff)  100.759 ms  100.537 ms  89.907 ms
 6  2001:4860::1:0:5db (2001:4860::1:0:5db)  115.563 ms  102.946 ms  106.191 ms
 7  2001:4860::2:0:a7 (2001:4860::2:0:a7)  101.754 ms  100.475 ms  100.512 ms
 8  2001:4860:0:1::c3 (2001:4860:0:1::c3)  99.272 ms  111.989 ms  99.835 ms
 9  yw-in-x67.1e100.net (2001:4860:8009::67)  101.545 ms  109.675 ms  99.431 ms

Upgrading Alpine Linux on CD

Boot media

If the boot media being used (such as a CD, for example) is separate from the media used to store the configuration information, simply download the latest ISO, and replace the boot media contents with the contents of the latest ISO.

If booting from a CD, this would simply mean replacing the CD with a CD made from the new image and rebooting the Alpine Linux box.

Update local package installations

If you have locally installed and configured additional packages using APK caching you should also perform the following steps.

Backup the local configuration prior to upgrading.

lbu ci

Repository Settings

First thing is to to edit or check the /etc/apk/repositories file.

Besides doing it manually (see below) this may be done using one of the following shortcuts.

  • Launching the corresponding Alpine setup script,


    and pressing e to edit /etc/apk/repositories. Then editing the repository lines to reflect the new version number.

  • Or, use a one-line command to edit all version numbers in the file «in place». Here’s how you’d change v2.5 to v2.6:

    sed -i -e ‘s/v2\.5/v2.6/g’ /etc/apk/repositories

Note, subsequent manual changes of the version numbers in /etc/apk/repositories may be avoided for future release upgrades by having the repository lines refer to «latest-stable» instead of an absolute value:

However, beware of initiating unexpected release upgrades.

Manual editing of /etc/apk/repositories:

Edit the /etc/apk/repositories file using an editor ( for instance) and if necessary, add references to the Alpine package repositories. In the example below, the file references the Alpine CD, so that if a requested package is available on the local media, it will be obtained from there instead of being downloaded from the remote repository:

Contents of /etc/apk/repositories


To upgrade, in this example, from version 3.3 to 3.4, simply change:


So that the file will look like this:

Contents of /etc/apk/repositories


Note: Starting with version 3.3, there is a new repository called community. Many packages have been moved from the main repository to the community repository to indicate that they are not guaranteed to be supported beyond six months. If you are using any of these packages, be sure to add the community repository. For example:

Above, only one possible repository is shown, however, may also be replaced with any geographically close mirror from:

Updating package lists

With the correct repositories file in place, the latest index list of available packages can be obtained with:

apk update

Tip: Adding the or to another apk command, as in or , has the same effect as always running immediately before the other apk command. Instead of auto-update it only if the index has not been updated recently.

Upgrading packages

At times it is required to first upgrade just the Alpine Linux Package Manager itself to the latest available version, before upgrading any other package. This was the case, for example, when upgrading from a version of Alpine before 2.3.0_rc1. But simply always doing so shounld’t hurt, either:

apk add —upgrade apk-tools

Next, to upgrade all installed packages:

apk upgrade —available

The switch is used to force all packages to be upgraded, even if they have the same version numbers. Sometimes changes in uClibc require doing this.

Note: All services that have been upgraded need to be restarted, to begin using the upgraded version. If the kernel is upgraded, it’s required to reboot to begin using the upgraded version:


After upgrading the packages, save the upgraded configuration changes.

lbu ci


This is the main Alpine configuration and installation script.

The script interactively walks the user through executing several auxiliary scripts, in the order shown below.

The bracketed options represent example configuration choices, formatted as they may be supplied when manually calling the auxiliary setup scripts, or using a «answerfile» (see below).

  1. if none of the networking interfaces were configured using dhcp, then: «]
  2. set the root password
  3. if not in quick mode, then: [-z UTC | -z America/New_York | -p EST+5]
  4. enable the new hostname ()
  5. add and to the boot rc level, and and to the default rc level, and start the boot and default rc services
  6. extract the fully-qualified domain name and hostname from /etc/resolv.conf and , and update /etc/hosts
  7. [-q «http://webproxy:8080»], and activate proxy if it was configured
  8. if not in quick mode, then:
  9. if not in quick mode, then:
  10. if not in quick mode, then: [-m data /dev/sda] (see about the disk modes)
  11. if installation mode selected during setup-disk was «data» instead of «sys», then: [/media/sdb1]
  12. if installation mode selected during setup-disk was «data» instead of «sys», then: [/media/sdb1/cache | none]

itself accepts the following command-line switches

Shows the up-to-date usage help message.
Create an overlay file: this creates a temporary directory and saves its location in ROOT; however, the script doesn’t export this variable so I think this feature isn’t currently functional.
-c answerfile
Create a new «answerfile», with default choices. You can edit the file and then invoke .
-f answerfile
Use an existing «answerfile», which may override some or all of the interactive prompts.
Run in «quick mode».

Настроить Alpine Linux

Когда вы, наконец, загрузитесь в свою новую установку Alpine, она все еще довольно проста, только с текстовой консолью и оболочкой. Вы захотите внести некоторые изменения в систему по умолчанию, чтобы сделать ее действительно полезной.

Настроить обычного пользователя

При первой установке Alpine единственным пользователем является root. Вы не хотите все время работать с правами root. Это угроза безопасности, и вы можете случайно повредить важные системные файлы.

Чтобы добавить еще одного пользователя, просто введите:

Вы замените «username» на имя пользователя, которого хотите использовать для входа в систему. Параметр -h указывает домашний каталог, а параметр -s указывает путь к оболочке, ash, которая является оболочкой по умолчанию для BusyBox и, следовательно, оболочки, установленной в Alpine Linux. Если вы хотите использовать другую оболочку, вы должны изменить этот параметр на путь к предпочитаемой оболочке.

Чтобы установить пароль для пользователя, используйте команду passwd :

Вам будет предложено установить пароль для пользователя. Повторно введите пароль, чтобы подтвердить процесс. Как только это будет сделано, вы можете выйти из учетной записи root и войти в свою учетную запись обычного пользователя.

По умолчанию, если вы хотите запускать команды от имени пользователя root, вы будете использовать команду su :

Параметр – означает запуск оболочки входа в систему, как если бы вы вошли напрямую в систему с правами root. При появлении запроса введите пароль root, после чего вам будет предложено приглашение #, которое указывает, что вы работаете как root. Когда вы закончите выполнение административных команд, лучше всего выйти из корневого сеанса, набрав logout или нажав Ctrl + D, чтобы вернуться к обычному сеансу.

Если вы привыкли использовать sudo, в документации есть информация о .

Управление пакетами

Как и в любом другом современном дистрибутиве Linux, Alpine использует диспетчер пакетов. Они создали свой собственный, названный Alpine Package Keeper, или APK.

Использовать APK очень просто. Если вы привыкли использовать Apt в Debian или Ubuntu , это еще проще. Неизвестно, было ли это намеренно, но многие команды идентичны.

Чтобы обновить репозиторий, просто введите эту команду:

Чтобы обновить свои пакеты до последних доступных, введите:

Чтобы установить конкретный пакет, в данном случае Vim, введите:

Чтобы удалить пакет, введите:

Если какие-либо пакеты больше не нужны после удаления, APK удалит их автоматически. Это отличается от APT, поскольку вам нужно запустить команду apt autoremove, чтобы сделать то же самое.

Настройка среды рабочего стола

Если вы не планируете устанавливать Alpine в качестве сервера, вы, вероятно, захотите установить графическую среду. К счастью, Alpine поддерживает основные оконные менеджеры и среды рабочего стола.

Для настройки X Alpine предоставляет скрипт setup-xorg-base . Это похоже на процесс установки, когда вы запускаете его и отвечаете на несколько вопросов о вашей настройке. В большинстве случаев настройка выполняется автоматически.

Вам придется самостоятельно установить предпочитаемый оконный менеджер, рабочий стол, файловый менеджер и т. Д. Вы, вероятно, также захотите установить диспетчер дисплея, такой как LightDM. Однако вам придется сказать OpenRC, чтобы он запускался автоматически.

Например, чтобы использовать LXDM;

by using from linux already started to new partition

  1. Alpine Install: from alpine mirror to a new computer by chroot, install Alpine on a real (i.e. not virtual) modern machine directly using the Alpine mirror sources if you will be using Alpine inside another Linux installation via chroot.
  2. Alpine Install: from alpine mirror to an external disc by chroot, install Alpine on a real (i.e. not virtual) modern machine directly using the Alpine mirror sources if you extracted the disc for use with an existing instance of Linux.
  3. Alpine Install: from a iso to a virtualbox machine with external disc, install Alpine on a VirtualBox external disc machine. Use if you have an older computer that doesn’t boot, but need to extract the disc to prepare it for use.

Ethernet Configuration

For the following Ethernet configuration examples, we will assume that you are using Ethernet device .

Add the following to the file , above any IP configuration for :

auto eth0

IPv4 DHCP Configuration

Add the following to the file , below the definition:

iface eth0 inet dhcp

By default, the busybox DHCP client (udhcpc) requests a static set of options from the DHCP server. If you need to extend this set, you can do so by setting some additional command line options for the DHCP client, via the in your interface configuration. The following example requests

iface eth0 inet dhcp
    udhcpc_opts -O search

IPv4 Static Address Configuration

Add the following to the file , below the definition:

iface eth0 inet static

Since Alpine 3.13 must be:

iface eth0 inet static

Additional IP addresses

iface eth0 inet static

iface eth0 inet static

Since Alpine 3.13 must be:

iface eth0 inet static

iface eth0 inet static

Add the following to the file , below the definition:

iface eth0 inet6 auto

IPv6 Static Address Configuration

Add the following to the file , below the definition:

iface eth0 inet6 static
        address 2001:470:ffff:ff::2
        netmask 64
        gateway 2001:470:ffff:ff::1
        pre-up echo 0 > /proc/sys/net/ipv6/conf/eth0/accept_ra

Since Alpine Linux 3.13 must be as:

iface eth0 inet6 static
        address 2001:470:ffff:ff::2/64
        gateway 2001:470:ffff:ff::1
        pre-up echo 0 > /proc/sys/net/ipv6/conf/eth0/accept_ra



If the Xorg server segfaults in kvm/qemu then add nomodeset as a boot option.

If the mouse / keyboard is not responding, you can try disabling hotplug.

  Section "ServerFlags"
    Option "AutoAddDevices" "False"


If you are unable to login, check /var/log/lightdm/lightdm.log, there may be output there from X to indicate failed modules, etc.

If you are unable to login, or you see an error «Failed to execute login command», you should check ~/.xinitrc (if you’re using .xinitrc) with your preferred text editor (vi, nano, etc) and ensure that it is set to load xfce. To do this, the ‘exec’ line (usually the last line in the file) should read «exec startxfce4». If ~/.xinitrc does not exist, create it and add the exec line. this command will do it:

$ echo «exec startxfce4» >> ~/.xinitrc


If the panel and windows disappear or start flickering after logging in to xfce the first time, log out, and then log in again. That happens because xfce is writing a default config file with the compositor enabled, but does not enable it during your first login. Clear out the ~/.config/xfce directory, and login as «first time» again, as the default vblank setting for the compositor is likely incorrect. Open the windows manager tweaks and dconf editor (or use dconf-query) before you log out. Tick the compositor to off in the window manager tweaks ui. If you have a recent enough xfce (4.14) there is a ui in window manager tweaks to set syncing mode, and you can try different values, such as vblank, xpresent, and glx, while turning the compositor on and off, until you find one that works. Or, from dconf editor, you can set xfwm4 /general/vblank_mode, which you will find is set to «auto» by default, and then turn the compositor on again. This can also be accomplished from the command line using using:

xfconf-query -c xfwm4 -p /general/vblank_mode -s mode

where mode is vblank, glx or xpresent.

You have to use xfconf-query from within the xfce terminal session, or at least with the xfce settings daemon started.


This is a standalone script; it’s not invoked by but must be run manually.

It configures a graphical environment, installing basic Xorg packages and udev (replacing mdev), and is also required for Wayland sessions.

The script installs, among other packages, e.g.: .

Additional packages to install may be supplied as arguments.


Video packages (optional)

You may install specific xf86 xorg driver packages for your video card’s chipset, as they may support specific features, effects and acceleration modes, and avoid error messages during X initialization.

However, the most basic X features should work fine with just using the default kernel video-modesetting drivers.

Info about the particular video cards that are installed in the computer may be found in the list of PCI devices:

# apk add pciutils
$ lspci

To see available video driver packages run:

$ apk search xf86-video

For example,

For an Sis video chipset install ‘xf86-video-sis’.

# apk add xf86-video-sis


For Intel video chipsets install ‘xf86-video-intel’ and see Intel Video.

Tip: In some cases, freezes on suspend/resume stop happening when changing the video port the monitor is connected to.

  • For AMD Radeon Video see Radeon_Video
  • For Alix1D use xf86-video-geode.
  • In KVM/QEMU guests see
  • In VirtualBox guests use xf86-video-vboxvideo, and install the VirtualBox guest additions as well. They contain important parts for the driver.
  • In VMware guests use xf86-video-vmware
  • In Hyper-V guests use xf86-video-fbdev and install the Hyper-V guest services as well.

Input packages

If the Numlock settings are not working, or getting ‘setleds not found’ errors:

# apk add kbd

If some input device is not working at all, the available xf86-input drivers can be listed with:

$ apk search xf86-input

Typical legacy drivers:

# apk add xf86-input-mouse xf86-input-keyboard

And for touchpad tapping support on many laptops, also:

# apk add xf86-input-synaptics

Configure xorg-server (optional)

On most systems, xorg should be able to autodetect all devices. However you can still configure xorg-server by hand by launching:

# Xorg -configure

This will create a `/root/xorg.conf.new` file. You can modify this file to fit your needs.
(When finished modifying and testing the above configuration file, move it to `/etc/X11/xorg.conf` for normal usage.)

Keyboard Layout (optional)

If you use a keyboard layout different than «us», and you are using a window manager or desktop environment that does not support to configure the keyboard layout itself, then you need to

Enable the «community» repository

and install setxkbmap:

# apk add setxkbmap

Then try

# setxkbmap <%a language layout from /usr/share/X11/xkb/rules/xorg.lst%>

In order to make it persistent add this section to /etc/X11/xorg.conf:

Section «InputClass»
Identifier «Keyboard Default»
MatchIsKeyboard «yes»
Option «XkbLayout» «<%a language layout from /usr/share/X11/xkb/rules/xorg.lst%>»

Another way to change the keymap when logging into X is to use ~/.xinitrc. The following example loads a British keymap, simply add this line to the beginning of the file:

If you need to create the ~/.xinitrc file, you may also want to add a second line like to still start the window manager with or .

apk info

The info command provides information on the contents of packages, their dependencies, and which files belong to a package.

For a given package, each element can be chosen (for example, -w to show just the webpage information), or all information displayed with the -a command.


apk info -a zlib

zlib-1.2.5-r1 description:
A compression/decompression Library

zlib-1.2.5-r1 webpage:

zlib-1.2.5-r1 installed size:

zlib-1.2.5-r1 depends on:

zlib-1.2.5-r1 is required by:

zlib-1.2.5-r1 contains:

zlib-1.2.5-r1 triggers:

As shown in the example you can determine

  • The description of the package (-d or —description)
  • The webpage where the application is hosted (-w or —webpage)
  • The size the package will require once installed (in bytes) (-s or —size)
  • What packages are required to use this one (depends) (-R or —depends)
  • What packages require this one to be installed (required by) (-r or —rdepends)
  • The contents of the package, that is, which files it installs (-L or —contents)
  • Any triggers this package sets. (-t or —triggers) Listed here are directories that are watched; if a change happens to the directory, then the trigger script is run at the end of the apk add/delete. For example, doing a depmod once after installing all packages that add kernel modules.

Tip: The info command is also useful to determine which package a file belongs to. For example:

apk info —who-owns /sbin/lbu

will display

/sbin/lbu is owned by alpine-conf-x.x-rx

Listing installed packages

To list all installed packages, use:

apk info

To list all installed packages in alphabetical order, with a description of each, do:

apk -vv info|sort

Repository pinning

You can specify additional «tagged» repositories in /etc/apk/repositories:

Contents of /etc/apk/repositories

@edge http://nl.alpinelinux.org/alpine/edge/main
@edgecommunity http://nl.alpinelinux.org/alpine/edge/community
@testing http://nl.alpinelinux.org/alpine/edge/testing

After which you can «pin» dependencies to these tags using:

apk add stableapp newapp@edge bleedingapp@testing

Apk will now by default only use the untagged repositories, but adding a tag to specific package:

1. will prefer the repository with that tag for the named package, even if a later version of the package is available in another repository

2. allows pulling in dependencies for the tagged package from the tagged repository (though it prefers to use untagged repositories to satisfy dependencies if possible)

Используйте лучший инструмент для работы

P.s. Спасибо моим коллегам из

Alpine Linux — один из самых компактных и нетребовательных к железу дистрибутивов Linux, ориентированных на безопасность пользователя. Зачастую его можно встретить во многих встраиваемых системах. Alpine Linux прекрасно подходит для таких задач как создания контейнеров, организации серверов или ознакомления с основами Линукс, поскольку дистрибутив не отягощён избыточным функционалом, но при этом поддерживает установку любой популярной графической среды. Дистрибутив основан на BusyBox вместо GNU coreutils. Alpine будет хорошим выбором для пользователей, которые ищут упрощенный вариант для работы с минимальным набором функций, при этом максимально эффективный и полезный:

  • Небольшое количество базовых компонентов, которые благоприятно сказываются на размерах оболочки — без ядра базовая система весит всего около 5 МБ;
  • Быстрая и простая установка через консольную утилиту;
  • Удобные настройки конфигурации системы пользователем;
  • В дистрибутиве применены свежие версии ядер, а также реализована возможность применять патчи, повышающие степень безопасности системы. Также реализована защита стека от переполнения.

apk policy

To display the repository a package was installed from and will be updated from, plus any or enabled repositories where it is also offered, if any, for this architecture — its policy:

apk policy package

For example:

 $ apk policy vlc
 vlc policy:
    @edgecommunity http://dl-3.alpinelinux.org/alpine/edge/community

Local Cache


To have the packages available during boot, apk can keep a cache of installed packages on a local disk.

Added packages can then be automatically (re-)installed from local media into RAM when booting, without requiring, and even before there is a network connection.

The cache can be stored on any writable media, or at the same location as the .apkovl file from the local backup utility .

Enabling Local Cache with current releases

Execute the script


and it will assist in enabling a local cache.

The script creates a symlink named /etc/apk/cache that points to the cache directory.

Cache maintenance

Removing older packages

When newer packages are added to the cache over time, the older versions of the packages default to remain in the cache directory.

The older versions of packages can be removed with the clean command.

apk cache clean

Or to see what is deleted include the verbose switch:

apk -v cache clean

Download missing packages

If you accidentally delete packages from the cache directory, you can make sure they are there with the download command,

apk cache download

Delete and download in one step

You can combine the two steps into one with the sync command — this cleans out old packages and downloads missing packages.

apk cache -v sync

Automatically Cleaning Cache on Reboot

To automatically attempt to validate your cache on reboot, you can add the above command to a /etc/local.d/*.stop file:

Contents of /etc/local.d/cache.stop


# verify the local cache on shutdown
apk cache -v sync

# We should always return 0
return 0

Tip: Usually the only time you need to reboot is when things have gone horribly wrong; so this is a «best effort» to cover forgetting to sync the cache; It is much better to run sync immediately after adding or upgrading packages.

Note: Custom shutdown commands were formerly added to a /etc/conf.d/local; but that method is now deprecated.

Special Caching Configurations

Enabling Local Cache on HDD installs

Note that HDD ‘sys’ installs don’t need an apk cache to maintain their state, it allows to serve packages over the network, though, e.g. to get installed by other local machines.

Manually create a cache dir and then symlink it to /etc/apk/cache:

mkdir -p /var/cache/apk
ln -s /var/cache/apk /etc/apk/cache

Local Cache on tmpfs volumes

In some circumstances it might be useful to have the cache reside on tmpfs, for example if you only wish for it to last as long as the system is up.

NOTE: apk is coded to ignore tmpfs caches, and this is correct behaviour in most instances. Using tmpfs as a package cache can consume large amounts of system memory if you install a lot of packages, possibly resulting in a crashed system. You can limit this by restricting the size of your cache to a small number (128M in the example below).

To do it, you need to create an image inside which your cache can live. We do this by creating an image file, formatting it with ext2, and mounting it at /etc/apk/cache.

  • apk add e2fsprogs
  • dd if=/dev/zero of=/apkcache.img bs=1M count=128
  • mkfs.ext2 -F /apkcache.img
  • mkdir -p /etc/apk/cache
  • mount -t ext2 /apkcache.img /etc/apk/cache
  • apk update

As usual, if you want to download currently installed packages into the cache, use apk cache sync.

Manually Enabling Local Cache (required for releases prior to v2.3)

  1. Create a cache directory on the storage device where you keep the lbu backups (typically, .)

    mkdir /media/sda1/cache

Tip: If you get an error that says «mkdir: can’t create directory ‘/media/usbdisk/cache’: Read-only file system», then you probably need to remount your disk read-write temporarily. Try

mount -o remount,rw /media/sda1

and then don’t forget to run

mount -o remount,ro /media/sda1

when you are done with the following commands

  1. Create a symlink to this directory from .

    ln -s /media/sda1/cache /etc/apk/cache

  2. Run an lbu commit to save the change ( is in and is automatically backed up.)

    lbu commit

Tip: If you needed to remount your disk read-write before, run

mount -o remount,ro /media/sda1

now that you are done with saving the changes

Now whenever you run an apk command that pulls a new package from a remote repository, the package is stored on your local media. On startup, Alpine Linux will check the local cache for new packages, and will install them if available.

Network browsing

For browsing of network shares within XFCE that works seamlessly with file associations, you can install the gvfs packages for the network protocols you use.

For example, to browse in a SMB/cifs windows network:

# apk add gvfs-smb

(Check: If the above may already be sufficient for gvfs to initiate the fuse kernel module. Else, try to identify if there are necessary steps in:)

# apk add gvfs-fuse

The OpenRC script for fuse is in a separate package.

# apk add fuse-openrc

Then the fuse service can be started manually.

# rc-service fuse start

(The XFCE sessions already in progress need to be restarted for this to take effect, i.e. log out and log in again.)

If it works, the fuse service can be added to start up automatically at boot time:

# rc-update add fuse

( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Ваша ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: