Lxc

Содержание:

Managing containers

Basic usage

To list all installed LXC containers:

# lxc-ls -f

Systemd can be used to start and to stop LXCs via . Enable to have it start when the host system boots.

Users can also start/stop LXCs without systemd.
Start a container:

# lxc-start -n CONTAINER_NAME

Stop a container:

# lxc-stop -n CONTAINER_NAME

To login into a container:

# lxc-console -n CONTAINER_NAME

Once logged, treat the container like any other linux system, set the root password, create users, install packages, etc.

To attach to a container:

# lxc-attach -n CONTAINER_NAME --clear-env

That works nearly the same as lxc-console, but it causes starts with a root prompt inside the container, bypassing login. Without the flag, the host will pass its own environment variables into the container (including , so some commands will not work when the containers are based on another distribution).

Advanced usage

LXC clones

Users with a need to run multiple containers can simplify administrative overhead (user management, system updates, etc.) by using snapshots. The strategy is to setup and keep up-to-date a single base container, then, as needed, clone (snapshot) it. The power in this strategy is that the disk space and system overhead are truly minimized since the snapshots use an overlayfs mount to only write out to disk, only the differences in data. The base system is read-only but changes to it in the snapshots are allowed via the overlayfs.

This article or section needs expansion.

Note: overlayfs for unprivileged containers is not supported in the current mainline Arch Linux kernel due to security considerations.

For example, setup a container as outlined above. We will call it «base» for the purposes of this guide. Now create 2 snapshots of «base» which we will call «snap1» and «snap2» with these commands:

# lxc-copy -n base -N snap1 -B overlayfs -s
# lxc-copy -n base -N snap2 -B overlayfs -s

Note: If a static IP was defined for the «base» lxc, that will need to manually changed in the config for «snap1» and for «snap2» before starting them. If the process is to be automated, a script using sed can do this automatically although this is beyond the scope of this wiki section.

The snapshots can be started/stopped like any other container. Users can optionally destroy the snapshots and all new data therein with the following command. Note that the underlying «base» lxc is untouched:

# lxc-destroy -n snap1 -f

Converting a privileged container to an unprivileged container

Once the system has been configured to use unprivileged containers (see, ), AUR contains a utility called which is able to convert an existing privileged container to an unprivileged container to avoid a total rebuild of the image.

Warning:

  • It is recommended to backup the existing image before using this utility!
  • This utility will not shift UIDs and GIDs in ACL, users will need to shift them manually!

Invoke the utility to convert over like so:

# uidmapshift -b /var/lib/lxc/foo 0 100000 65536

Additional options are available simply by calling without any arguments.

EXAMPLES top

       To spawn a new shell running inside an existing container, use

                 lxc-attach -n container

       To restart the cron service of a running Debian container, use

                 lxc-attach -n container -- /etc/init.d/cron restart

       To deactivate the network link eth1 of a running container that does
       not have the NET_ADMIN capability, use either the -e option to use
       increased capabilities, assuming the ip tool is installed:

                 lxc-attach -n container -e -- /sbin/ip link delete eth1

       Or, alternatively, use the -s to use the tools installed on the host
       outside the container:

                 lxc-attach -n container -s NETWORK -- /sbin/ip link delete eth1

Basic usage

LXC can be used in two distinct ways — privileged, by running the lxc commands as the root user; or unprivileged, by running the lxc commands as a non-root user. (The starting of unprivileged containers by the root user is possible, but not described here.) Unprivileged containers are more limited, for instance being unable to create device nodes or mount block-backed filesystems. However they are less dangerous to the host, as the root UID in the container is mapped to a non-root UID on the host.

Basic privileged usage

To create a privileged container, you can simply do:

or, abbreviated

This will interactively ask for a container root filesystem type to download – in particular the distribution, release, and architecture. To create the container non-interactively, you can specify these values on the command line:

or

You can now use to list containers, to obtain detailed container information, to start and to stop the container. and allow you to enter a container, if ssh is not an option. removes the container, including its rootfs. See the manual pages for more information on each command. An example session might look like:

User namespaces

Unprivileged containers allow users to create and administer containers without having any root privilege. The feature underpinning this is called user namespaces. User namespaces are hierarchical, with privileged tasks in a parent namespace being able to map its ids into child namespaces. By default every task on the host runs in the initial user namespace, where the full range of ids is mapped onto the full range. This can be seen by looking at and , which both will show when read from the initial user namespace. As of Ubuntu 14.04, when new users are created they are by default offered a range of UIDs. The list of assigned ids can be seen in the files and See their respective manpages for more information. Subuids and subgids are by convention started at id 100000 to avoid conflicting with system users.

If a user was created on an earlier release, it can be granted a range of ids using , as follows:

The programs and are setuid-root programs in the package, which are used internally by lxc to map subuids and subgids from the host into the unprivileged container. They ensure that the user only maps ids which are authorized by the host configuration.

Basic unprivileged usage

To create unprivileged containers, a few first steps are needed. You will need to create a default container configuration file, specifying your desired id mappings and network setup, as well as configure the host to allow the unprivileged user to hook into the host network. The example below assumes that your mapped user and group id ranges are 100000–165536. Check your actual user and group id ranges and modify the example accordingly:

After this, you can create unprivileged containers the same way as privileged ones, simply without using sudo.

Nesting

In order to run containers inside containers — referred to as nested containers — two lines must be present in the parent container configuration file:

The first will cause the cgroup manager socket to be bound into the container, so that lxc inside the container is able to administer cgroups for its nested containers. The second causes the container to run in a looser Apparmor policy which allows the container to do the mounting required for starting containers. Note that this policy, when used with a privileged container, is much less safe than the regular policy or an unprivileged container. See the Apparmor section for more information.

Возможности

Самая полезная часть статьи — рецепты, как и что можно использовать с помощью LXD

Поехали

Инициализация LXD

Первый запуск предупредит о том, что мы должны инициализировать через команду lxd_init систему контейнеризации, то есть указать начальные настройки. Запускаем и дальше как по мастеру. Отвечаем на вопросы по своему вкусу.

Положить/забрать файл из контейнера.

LXC предоставляет хорошие возможности для управления контейнерами «на лету». Вот так, например, можно поместить созданный на основном хосте файл внутрь контейнера:

Можно совершить и обратную операцию — загрузить файл из контейнера на основной хост:

Можно и редактировать файлы в контейнере напрямую:

Создать общий ресурс

Импорт различных образов

LXD основан на образах. Контейнеры создаются из образа, поэтому хранилище образов должно содержать несколько образов перед основной работой с LXD.
Есть несколько путей заполнить хранилище:

  • Используя удаленный LXD как сервер образов
  • Используя встроенные источники образов
  • Вручную импортируя по одному

Связать с определннным мостом и задать статический IPv4 адрес

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

Редактируем файл «/etc/default/lxc-net» и меняем

на

Переместить пул хранилища

Я люблю хранить все конфигурации в определенном мною месте, поэтому тут способ, как переместить дефолтное хранилище наиболее безболезненно.

Останавливаем LXD, перемещаем содержимое /var/lib/lxd в новую директорию, после этого делаем симлинк на новое место, и можно запускать LXD

Проброс устройств

Шикарная возможность, позволяющая пробрасывать устройства внутрь контейнера, основываясь на vendor/product id, так как многие usb устройства любят менять свой номер устройства на шине pci (в листинге вывода lsusb). Подробнее по параметрам .

Автозапуск контейнера при запуске основной системы

Флаг автозапуска и приоритеты запуска, для того, чтобы определить очередность запуска контейнеров и задержку перед запуском

Troubleshooting

Logging

If something goes wrong when starting a container, the first step should be to get full logging from LXC:

This will cause lxc to log at the most verbose level, , and to output log information to a file called ‘debug.out’. If the file already exists, the new log information will be appended.

Monitoring container status

Two commands are available to monitor container state changes. monitors one or more containers for any state changes. It takes a container name as usual with the -n option, but in this case the container name can be a posix regular expression to allow monitoring desirable sets of containers. continues running as it prints container changes. waits for a specific state change and then exits. For instance,

would print all state changes to any containers matching the listed regular expression, whereas

will wait until container cont1 enters state STOPPED or state FROZEN and then exit.

Attach

As of Ubuntu 14.04, it is possible to attach to a container’s namespaces. The simplest case is to simply do

which will start a shell attached to C1’s namespaces, or, effectively inside the container. The attach functionality is very flexible, allowing attaching to a subset of the container’s namespaces and security context. See the manual page for more information.

Container init verbosity

If LXC completes the container startup, but the container init fails to complete (for instance, no login prompt is shown), it can be useful to request additional verbosity from the init process. For an upstart container, this might be:

You can also start an entirely different program in place of init, for instance

Быстрая установка LXC в Debian GNU/Linux

Установка среды изоляции и управления LXC очень проста, все необходимое для работы уже содержится в официальных пакетах для GNU/Linux, поэтому нужно выполнить лишь несколько команд и провести простую настройку.

Установка свежего пакета lxc:

Установка пройдет быстро, размер закачиваемых пакетов составит всего лишь несколько мегабайт.

Проверка конфигурации и доступных возможностей:

Теперь, если с конфигурацией все хорошо, осталось настроить и включить сетевой мост для контейнеров. Сперва откроем в редакторе файл ‘lxc-net’:

Добавим в этот файл строчку:

Сохраним файл и выйдем из редактора (CTRL+X, Y).

Изменим шаблон с опциями настройки сети для контейнеров, отредактируем файл default.conf:

Заменим все его содержимое следующим:

Сохраняем файл и выходим.

Перезапустим сетевую службу для LXC:

Проверим создан ли интерфейс виртуального сетевого моста — lxcbr0:

Если интерфейс присутствует в списке — значит сетевой мост настроен, можно приступать к работе с LXC контейнерами!

IP-адрес и маска сети хоста по умолчанию — 10.0.3.1/24, контейнеры будут получать IP-адреса из подсети 10.0.3.0/24.

Хочу обратить внимание что данной конфигурации вполне достаточно для работы из под привилегированного пользователя (root), но не достаточно для выполнения команд от имени обычного пользователя. При запуске lxc-команд от пользователя root и от обычного пользователя — размещение контейнеров и файлов с настройками LXC будут отличаться!

При запуске lxc-команд от пользователя root и от обычного пользователя — размещение контейнеров и файлов с настройками LXC будут отличаться!

О настройке и запуске контейнеров от имени непривилегированного пользователя можно узнать на страничке .

4 ответа

Файловая система EXT4 + TRIM:

  • EXT4 с TRIM повышает производительность за счет сокращения ненужной записи циклов на накопитель SSD, поскольку они ограничивают цикл записи-перезаписи.
  • Ubuntu и некоторые другие варианты Linux поддерживают EXT 4 с TRIM из коробки.

SWAP-раздел:

  • Убедитесь, что у вас нет пространства SWAP на SSD, чтобы уменьшить циклы записи.
  • Если у вас есть механический диск, вам необходимо создать пространство SWAP на механическом диске и избегать его на SSD.

Разделение разделов:

Поэтому используйте EXT4 + TRIM с SWAP на механическом жестком диске или без SWAP на SSD.

Выберите ext4 и установите его с помощью опции discard для TRIM или используйте FITRIM (см. ниже). Также используйте опцию noatime , если вы боитесь «износа SSD».

Не изменяйте планировщик ввода-вывода по умолчанию (CFQ) на серверах нескольких приложений , поскольку он обеспечивает справедливость между процессами и поддерживает автоматическую SSD-поддержку , Однако используйте Deadline на десктопах , чтобы получить лучшую отзывчивость при загрузке.

Чтобы легко гарантировать правильное выравнивание данных, начальный сектор каждого раздела должен быть кратным 2048 (= 1 MiB). Вы можете использовать fdisk -cu /dev/sdX для их создания. В последних дистрибутивах он автоматически позаботится об этом для вас.

Подумайте дважды, прежде чем использовать swap на SSD. . Это, вероятно, будет намного быстрее по сравнению с swap на HDD, но он также будет быстрее носить диск (что может быть не актуально, см. ниже ).

Ext4 — самая распространенная файловая система Linux (в хорошем состоянии). Он обеспечивает хорошую производительность с помощью SSD и поддерживает функцию TRIM (и FITRIM), чтобы поддерживать хорошую производительность SSD с течением времени (это позволяет удалить неиспользуемые блоки памяти для быстрого доступа к записи). NILFS специально разработан для флеш-накопителей, но не действительно работает лучше, чем ext4 в тестах. Btrfs по-прежнему считается экспериментальным (и на самом деле не работает лучше либо ).

Производительность SSD и amp; TRIM:

Функция TRIM очищает блоки SSD, которые больше не используются файловой системой. Это позволит оптимизировать долговременную производительность записи и рекомендуется на SSD из-за их дизайна. Это означает, что файловая система должна быть способна сообщить диску об этих блоках. Опция discard для ext4 выдаст такие команды TRIM , когда блоки файловой системы будут освобождены. Это онлайн-сброс .

Однако это поведение подразумевает небольшие накладные расходы. Начиная с Linux 2.6.37, вы можете избежать использования discard и выбрать вариант batch discard вместо FITRIM (например, из crontab). Утилита fstrim делает это (онлайн), а также параметр -E discard fsck.ext4 . Однако вам понадобится «последняя» версия этих инструментов.

Возможно, вы захотите ограничить запись на вашем диске, поскольку SSD имеет ограниченный срок службы в этом отношении. Не волнуйтесь слишком много, но , сегодня самый плохой SSD на 128 ГБ может поддерживать как минимум 20 ГБ письменных данных в день более 5 лет (1000 циклов записи на ячейку) , Более лучшие (и более крупные) могут длиться намного дольше: вы, вероятно, скорее всего замените его к тому времени.

Если вы хотите использовать swap на SSD, ядро ​​заметит невращающийся диск и будет рандомизировать использование swap (уровень износа уровня ядра): тогда вы см. SS (Solid State) в сообщении ядра при включении swap:

Добавление замены 2097148k в /dev /sda1. Приоритет: -1 экстентов: 1 через: 2097148k SS

Планировщики ввода /вывода:

Кроме того, я согласен с большинством ответов aliasgar (даже если большинство из них было — нелегально? — скопировано из этот веб-сайт ), но я должен частичноне согласны с частью планировщик . По умолчанию планировщик сроков оптимизирован для вращательных дисков, поскольку он реализует алгоритм лифта . Итак, давайте проясним эту часть.

Privileged containers or unprivileged containers

LXCs can be setup to run in either privileged or unprivileged configurations.

The Arch , and kernel packages currently provide out-of-the-box support for unprivileged containers. Similarly, with the package, unprivileged containers are only available for the system administrator; with additional kernel configuration changes required, as user namespaces are disabled by default for normal users there. This article contains information for users to run either type of container, but may be required in order to use unprivileged containers.

An example to illustrate unprivileged containers

To illustrate the power of UID mapping, consider the output below from a running, unprivileged container. Therein, we see the containerized processes owned by the containerized root user in the output of :

# ps -ef | head -n 5
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 17:49 ?        00:00:00 /sbin/init
root        14     1  0 17:49 ?        00:00:00 /usr/lib/systemd/systemd-journald
dbus        25     1  0 17:49 ?        00:00:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
systemd+    26     1  0 17:49 ?        00:00:00 /usr/lib/systemd/systemd-networkd

On the host, however, those containerized root processes are actually shown to be running as the mapped user (ID>100000), rather than the host’s actual root user:

# lxc-info -Ssip --name sandbox
State:          RUNNING
PID:            26204
CPU use:        10.51 seconds
BlkIO use:      244.00 KiB
Memory use:     13.09 MiB
KMem use:       7.21 MiB
# ps -ef | grep 26204 | head -n 5
UID        PID  PPID  C STIME TTY          TIME CMD
100000   26204 26200  0 12:49 ?        00:00:00 /sbin/init
100000   26256 26204  0 12:49 ?        00:00:00 /usr/lib/systemd/systemd-journald
100081   26282 26204  0 12:49 ?        00:00:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
100000   26284 26204  0 12:49 ?        00:00:00 /usr/lib/systemd/systemd-logind

Диагностика и решение проблем с сетевой подсистемой

Может случиться так, что в какой-то момент (после высокой загруженности сервера, перевода лептопа в спящий режим и т.п.) созданный LXC контейнер потерял свой IP-адрес или же и вовсе создаваемые контейнеры перестали получать сетевые настройки.

В такой ситуации, первым делом нужно проверить работу сервисов на хост-машине. Смотрим присутствует ли в системе сетевой интерфейс (мост, bridge) для LXC-контейнеров и каковы его настройки:

Если с этим интерфейсом все хорошо, то в результате исполнения команды увидим IP-адрес моста и другие параметры:

Для получения контейнерами сетевых настроек от хостовой машины механизмом LXC используется служба «dnsmasque», проверяем запущена ли она:

Если служба работает и присутствует в процессах, то в выводе вышеуказанной команды мы увидим строку, где будет указан PID процесса и его параметры, например (для удобства чтения я перенес параметры в отдельные строчки):

Как видим, здесь указан интерфейс и IP-адрес сетевого моста, на котором работает служба, а также пул адресов, доступный для присваивания LXC-контейнерам (2-254).

Теперь переходим к диагностике сети внутри контейнера, приведенные ниже команды должны выполняться в консоли запущенного LXC-контейнера.

Смотрим список доступных и активных сетевых интерфейсов внутри контейнера:

При настройках по умолчанию, как правило, в списке должны присутствовать минимум 2 сетевых интерфейса:

  • lo — loopback (локальная петля), локальный сетевой интерфейс;
  • eth0 — сетевой интерфейс, связанный с хост-машиной.

Если у сетевого интерфейса eth0 нет IP-адреса, то возможно что причина таится где-то в самом контейнере и его службах.

Посмотрим получил ли контейнер список DNS-серверов от сервиса dnsmasq, запущенного на хост-машине, выполним команду внутри контейнера:

В случае если все сконфигурировано правильно, в выводе получим строчку:

Если же полученных настроек IP-адреса и DNS-сервера в контейнере нет, то можем заставить его сделать повторную попытку получения этих сетевых настроек по протоколу DHCP от хост-машины:

Теперь можем пропинговать какой-то сайт и проверить корректно получены ли сетевые настройки:

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

Очень вероятно что проблему удастся решить перезапуском сетевой службы LXC на хост-машине:

Для перезапуска всего механизма LXC:

Если и это не помогло, то может быть что где-то сбились основные настройки сети LXC, стоит перепроверить все параметры, которые были задействованы .

Еще не помешает проверить правила файрвола IPTables, которые могут блокировать сетевые пакеты на пути от хост-машины к контейнерам.

В более сложных случаях возможна даже не работоспособность самой службы «dnsmasq», нужно изучить ее логи и на основе этих данных устранить проблему.

External mounts inside the container

By default only the container’s filesystem is mounted inside the container (even if on the host, /var/lib/lxc/mycontainer/rootfs has other mount points).

To mount another filesystem in the container, add to /var/lib/lxc/mycontainer/config:

lxc.mount.entry=/path/in/host/mount_point mount_point_in_container none bind 0 0

Another bind mount example:

# Exposes /dev/sde in the container
lxc.mount.entry = /dev/sde dev/sde none bind,optional,create=file

To mount in another filesystem (for example LVM) to a container mount point

lxc.mount.entry = /dev/mapper/lvmfs-home-partition home ext4 defaults 0 2

NOTE that it is critical to have no leading «/» in the container mount point (making it a relative mount point).

Mounts in unprivileged containers

When a container is , UID or GID of a mounted device has to be root in the container. To make sure this, do chgrp 100000 /dev/nvidiactl etc. on the host (assuming GID 100000 is container’s root group).

On the other hand, when host’s /home is mounted in an unprivileged container by

lxc.mount.entry = /home home none bind,rw 0 0

its UID/GID cannot be altered. To enable UID 1000 in an unprivileged container to access files of UID 1000 in /home on the host, we have to adjust UID/GID mapping between the host and the container as follows:

# Container's UID/GID 0-65535 are mapped to host's 100000-165535,
# but UID/GID 1000 on the container is mapped to host's UID/GID 1000.
lxc.idmap = u 0 100000 1000
lxc.idmap = g 0 100000 1000
lxc.idmap = u 1000 1000 1
lxc.idmap = g 1000 1000 1
lxc.idmap = u 1001 101001 64535
lxc.idmap = g 1001 101001 64535

Cloning

For rapid provisioning, you may wish to customize a canonical container according to your needs and then make multiple copies of it. This can be done with the program.

Clones are either snapshots or copies of another container. A copy is a new container copied from the original, and takes as much space on the host as the original. A snapshot exploits the underlying backing store’s snapshotting ability to make a copy-on-write container referencing the first. Snapshots can be created from btrfs, LVM, zfs, and directory backed containers. Each backing store has its own peculiarities — for instance, LVM containers which are not thinpool-provisioned cannot support snapshots of snapshots; zfs containers with snapshots cannot be removed until all snapshots are released; LVM containers must be more carefully planned as the underlying filesystem may not support growing; btrfs does not suffer any of these shortcomings, but suffers from reduced fsync performance causing dpkg and apt to be slower.

Snapshots of directory-packed containers are created using the overlay filesystem. For instance, a privileged directory-backed container C1 will have its root filesystem under . A snapshot clone of C1 called C2 will be started with C1’s rootfs mounted readonly under . Importantly, in this case C1 should not be allowed to run or be removed while C2 is running. It is advised instead to consider C1 a canonical base container, and to only use its snapshots.

Given an existing container called C1, a copy can be created using:

A snapshot can be created using:

See the lxc-clone manpage for more information.

Snapshots

To more easily support the use of snapshot clones for iterative container development, LXC supports snapshots. When working on a container C1, before making a potentially dangerous or hard-to-revert change, you can create a snapshot

which is a snapshot-clone called ‘snap0’ under /var/lib/lxcsnaps or $HOME/.local/share/lxcsnaps. The next snapshot will be called ‘snap1’, etc. Existing snapshots can be listed using , and a snapshot can be restored — erasing the current C1 container — using . After the restore command, the snap1 snapshot continues to exist, and the previous C1 is erased and replaced with the snap1 snapshot.

Snapshots are supported for btrfs, lvm, zfs, and overlayfs containers. If lxc-snapshot is called on a directory-backed container, an error will be logged and the snapshot will be created as a copy-clone. The reason for this is that if the user creates an overlayfs snapshot of a directory-backed container and then makes changes to the directory-backed container, then the original container changes will be partially reflected in the snapshot. If snapshots of a directory backed container C1 are desired, then an overlayfs clone of C1 should be created, C1 should not be touched again, and the overlayfs clone can be edited and snapshotted at will, as such

Ephemeral Containers

While snapshots are useful for longer-term incremental development of images, ephemeral containers utilize snapshots for quick, single-use throwaway containers. Given a base container C1, you can start an ephemeral container using

The container begins as a snapshot of C1. Instructions for logging into the container will be printed to the console. After shutdown, the ephemeral container will be destroyed. See the lxc-start-ephemeral manual page for more options.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *