- Docker
- Contents
- Installation
- Docker Compose
- Isolate containers with a user namespace
- Example: How to install docker from Arch
- «WARNING: No
limit support» - Alpine 3.8
- Extlinux
- How to use docker
- How to install Docker CE on Alpine Linux
- Steps to install Docker on Alpine Linux
- Step 1: Download and Setup Alpine Linux
- Step 2: Command to install Docker on Alpine
- Step 3: Apk add fails with unsatisfiable constraints error
- Step 4: Add Docker service to the system boot level
- Step 5: Install Docker Compose
- Step 6: Isolate containers with a user namespace
- Step 7: Now, check your install Docker
- Step 8 Pull Docker image on Alpine
- Additional: Errors we encountered while setting it up
- How to install docker on Alpine Linux VM
- Introduction
- Create Alpine VM on Proxmox
- Initial Setup
- Install qemu-guest-agent [optional]
- Install Docker Engine
- Alpine собирает Docker билды под Python в 50 раз медленней, а образы в 2 раза тяжелей
- Почему люди рекомендуют Alpine?
- Python образ
- Alpine не поддерживает wheels
- Alpine может быть причиной неожиданных багов в рантайме
- Так ли мал Alpine 3.8 Docker для Python 3 runtime
- Шаг 2. Установка cython и tornado
- Шаг 3. Добавляем математику numpy scipy
- Шаг 4. Добавляем графический стек websocket-client pytest pandas bokeh pillow
- Итоги
Docker
Contents
Installation
The Docker package is in the ‘Community’ repository. See Alpine_Linux_package_management how to add a repository.
Connecting to the Docker daemon through its socket requires you to add yourself to the `docker` group.
To start the Docker daemon at boot, see Alpine_Linux_Init_System.
For more information, have a look at the corresponding Github issue.
This weakening of security is not necessary to do with Alpine 3.4.x and Docker 1.12 as of August 2016.
Docker Compose
‘docker-compose’ is in the ‘Community’ repository starting with Alpine Linux 3.10.
For older releases:
To install docker-compose, first install pip:
Isolate containers with a user namespace
add to /etc/docker/daemon.json
You may also consider these options : ‘
You’ll find all possible configurations here[1].
Example: How to install docker from Arch
«WARNING: No limit support»
You might encounter this message when executing docker info . To correct this situation, we have to enable the cgroup_enable=memory swapaccount=1
Alpine 3.8
It may not have been the case before, but with Alpine 3.8, you must config cgroups properly
Warning: This seems not to work with Alpine 3.9 and Docker 18.06. Follow the instructions for grub or extlinux below instead.
If you use Grub, add the cgroup condition into /etc/default/grub , then upgrade your grub
Extlinux
With Extlinux, you add the cgroup condition, but inside of /etc/update-extlinux.conf
then update the config and reboot
How to use docker
The best documentation on using Docker and creating containers is at the main docker site. Adding anything to it here would be redundant.
If you create an account at docker.com, you can browse through user images and learn from the syntax in contributed dockerfiles.
Official Docker image files are denoted on the website by a blue ribbon.
Источник
How to install Docker CE on Alpine Linux
For Docker containers, Alpine Linux is an optimum choice because of lightweight, low RAM consumption and optimization. However, yet Ubuntu is the best.
Alpine Linux is a free and open-source Linux operating system for routers, firewalls, VPNs, VoIP computers, servers, virtual machines and containers. It has proactive security features that prevent security holes in the software from being exploited. The small, lightweight Linux distribution based on musl libc and busybox.
Steps to install Docker on Alpine Linux
I am not going to talk much on Docker here because if you are reading this tutorial then you would already know what it is. Well, in short Docker is a containerized Virtualization platform that allows running different virtual machines in the form of isolated containers. The best thing about it, lightweight and easy to handle; one can simply pull existing Linux or apps images to setup a container from hub.docker.com.
Step 1: Download and Setup Alpine Linux
If you already have a working Alpine Linux then simply move to the next step and if not then go to this link and download one . Alpine Linux is available in multiple forms such as Standard, Extended with some extra packages, Net-install, Optimized Virtual ISO image, for Xen with built-in support for Xen Hypervisor and in Minimal root filesystem for containers. You can download one as per your choice, however, here we are using Alpine Linux Extended version 3.11.
After downloading boot your PC or VirtualBox with it and run the command setup-alpine to follow the installation steps.
Step 2: Command to install Docker on Alpine
Run the following single command to fetch Docker packages for its installation on Alpine.
Step 3: Apk add fails with unsatisfiable constraints error
Incase after executing the above command you get an error “apk add fails with unsatisfiable constraints” then we have to add the following repository to Alpine.
Edit the Alpine repository file:
Then press Insert button on the keyboard and add the following line in the file.
To save and exit first press Esc and then type :wq after that press the Enter button.
Once you are done, run the package update command to let the system know about the updated repository, so that it can index the same.
Step 4: Add Docker service to the system boot level
To make sure the service of Docker gets automatically started every time along with the boot of the Alpine, we have to add it to our system services.
Now, we can start the Docker service
Step 5: Install Docker Compose
Users those also want the Docker Compose on Alpine, first, they have to install pip.
Few dev dependencies
Finally, run command to install docker-compose
Step 6: Isolate containers with a user namespace
Step 7: Now, check your install Docker
Use below command to check information of installed Docker version.
Step 8 Pull Docker image on Alpine
To know everything is working fine, let’s pull up a hello-world image
To run the image:
Additional: Errors we encountered while setting it up
1: error response from daemon https //registry-1.docker.io/v2/ time out
We got the above error because in the resolv.conf of Alpine the nameservers were not configured appropriately, thus we edited it:
And added the following nameservers:
2. After installing the Alpine, the network was unreachable, thus we edited:
And added the following:
In this way, we can use this lightweight Alpine Linux for Docker running containerized virtual machines.
Источник
How to install docker on Alpine Linux VM
Introduction
Alpine linux is a lighweight linux distro, making it small, fast and ideal for VM’s when server resources are limited. Especially when talking about running docker containers, a VM is the only way to go since LXC containers are not supported and its hacky to make docker run inside an LXC.
The Docker containers can be administered through the command line or by using a GUI tool.The two most lightweight administration tools are:
- Cockpit, it can run only in systemd distros so it is not an option for Alpine.
- Portainer, comes as a docker container, ideal for Alpine.
Following are the steps required to configure an Alpine system and install Docker.
Create Alpine VM on Proxmox
Download the latest .iso from Virtual category in https://alpinelinux.org/downloads/ .
Upload it to Proxmox VE from gui and create VM.
Typical example settings with one network card on Intel Core2 quad core PC
-
- OS -> Other OS types
- CD/DVD -> Use disk image (iso)
- Hard Disk -> Bus/Device IDE 0 , Storage local-lvm, Cache Default (no cache)
- CPU -> Type Default(kvm64)
- Memory -> Auto allocate and input the desired range
- Network -> Bridged mode , Model VirtIO (paravirtualized)
Again these are suggested defaults and depend on the machine and the network plan we have in mind.
Initial Setup
Still in Proxmox GUI , go to the new VM’s console, login as root and type:
and answer the questions of the wizard,including changing the root password.Alpine setup is possibly the easiest linux setup.Defaults are fine except in the disk creation.After selecting disk (sda) and purpose (sys), at least for this simple use case, type (y) in the warning:erase the above disk and continue ? question.
Alpine will prepare the portion of the hard disk allocated to our VM and will ask to reboot.
After rebooting the vm, from the proxmox console of the Alpine VM create a group and a user so we can ssh to the vm remotely from the terminal of our choice and not be bound to the builtin console of the proxmox GUI anymore:
We use docker group name on purpose because it will be needed later.
Now add the user in sudoers file to be able to execute all commands:
add anywhere this line:
Now press ESC and :wq to save and exit the editor. :q! to exit without saving.
Note:If for any reason we need to ssh as root,from proxmox GUI console:
and replace #permitrootlogin no with permitrootlogin yes .Save and exit the editor.Then restart ssh service:
Now we can leave the proxmox console and ssh to the server from another machine:
Install qemu-guest-agent [optional]
Install Docker Engine
We need to add the community repository in alpine that contains docker:
Now update the repositories, check that docker is present in apk and install:
Источник
Alpine собирает Docker билды под Python в 50 раз медленней, а образы в 2 раза тяжелей
Alpine Linux — часто рекомендованный как базовый образ для Docker`а. Вам говорят, что использование Alpine сделает ваши билды меньше, а процесс сборки быстрей.
Но если вы используете Alpine Linux для Python приложений, то он:
- Делает ваши билды намного медленней
- Делает ваши образы больше
- Тратит ваше время
- И в итоге может стать причиной ошибок в рантайме
Давайте рассмотрим почему же Alpine рекомендуют, но почему вам все же не стоит использовать его вместе с Python.
Почему люди рекомендуют Alpine?
Давайте предположим, что нам необходим gcc как часть нашего образа и мы хотим сравнить Alpine Linux vs Ubuntu 18.04, по скорости сборки и конечному размеру образа.
Для начала, скачаем два образа и сравним их размер:
Как вы видите, базовый образ для Alpine намного меньше. Давайте теперь попробуем установить gcc и начнем с Ubuntu:
Написание идеальных Dockerfile выходит за рамки этой статьи
Замерим скорость сборки:
Повторяем все то же самое для Alpine (Dockerfile):
Собираем, смотрим на время и размер сборки:
Как и обещано, образы на базе Alpine собираются быстрей и сами по себе меньше: 15 секунда вместо 30 и размер образа 105MB против 150MB. Это довольно хорошо!
Но если мы переключимся на сборку Python приложения, то все не так радужно.
Python образ
Python приложения часто используют pandas и matplotlib. Поэтому, один из вариантов взять официальный образ на базе Debian, используя такой Dockerfile:
Получаем образ размером в 363MB.
Получится у нас лучше с Alpine? Давайте попробуем:
Alpine не поддерживает wheels
Если вы посмотрите на билд, который базируется на Debian, то вы увидите, что он скачивает matplotlib-3.1.2-cp38-cp38-manylinux1_x86_64.whl.
Это бинарник для wheel. Alpine же скачивает исходники `matplotlib-3.1.2.tar.gz`, так как он не поддерживает стандартный wheels.
Почему? Большинство Linux дистрибутивов используют GNU версию (glibc) стандартной библиотеки C, который по факту необходим каждой программе написанной на C, включая Python. Но Alpine использует `musl`, а так как те бинарники предназначены для `glibc`, они попросту не вариант.
Поэтому, если вы используете Alpine, вам необходимо компилировать весь код, написанный на C, в каждом пакете Python.
Ах, да, список всех таких зависимостей которые, нужно компилировать придется искать самим.
В данном случае получаем такое:
И время билда занимает…
… 25 минут 57 секунд! А размер образа 851MB.
Образы на базе Alpine собираются намного дольше, сами по себе они большего размера и вам еще нужно искать все зависимости. Можно конечно уменьшить размер сборки используя multi-stage builds но это означает, что нужно проделать еще больше работы.
Alpine может быть причиной неожиданных багов в рантайме
- В теории musl совместим с glibc, но на практике различия могут стать причиной многих проблем. И если они будут, то наверняка неприяные. Вот некоторые проблемы, которые могут возникнуть:
- Alpine по умолчанию имеет меньший размер стека потока, что может привести к ошибкам в Python
- Некоторые пользователи обнаружили, что Python приложения работают медленней из-за того как, musl выделяет память (отличается от glibc).
- Один из пользователей обнаружил ошибку при форматировании даты
Наверняка эти ошибки уже исправили, но кто знает сколько их еще.
Источник
Так ли мал Alpine 3.8 Docker для Python 3 runtime
Совсем недавно произошёл релиз минималистичного Alpine Linux 3.8. Очень часто данный linux образ используют в докере, собирая очень компактные окружения для runtime.
Сегодняшняя статья будет рассмотрена в срезе использования runtime системы в докере для Python 3.6.X версий, с различным составом пакетов pip. А так же мы соберём самый новый Python 3.7 в Alpine.
В конце статьи будет представлен размер образа image, занимаемый на диске, в зависимости от состава пакетов pip и произведено сравнение между дистрибутивами Alpine 3.8, Debian 9, Fedora 28.
Итак, приступим: для тестирования дистрибутивы выбраны. Будем собирать следующие docker images:
- Система, ее обновление. И Python3 с обновлённым pip (10 версии)
- п.1 + tornado cython
- п.2 + numpy-scipy
- п.3 + pillow bokeh pandas websocket-client
В результате даных заливок, мы получим различные версии: Python без пакетов, Python с web сервером, Python с пакетами для обработки многопоточных математических вычислений, Python с «графическим» стеком и работы с данными.
Итак, результирующие файлы для Debian и Fedora будут выглядеть у нас так:
Debian
А вот с Alpine 3.8 пока заминка. Официально на момент написания статьи он ещё на вышел, а посмотреть, то хочется:-). Поэтому нам понадобиться их образ системы:
dl-cdn.alpinelinux.org/alpine/v3.8/releases/x86_64
И мы соберём свой Alpine from Sratch:
github.com/gliderlabs/docker-alpine/tree/master/versions/library-3.8/x86_64
Создаём свой докер файл:
Затем копипастим и добавляем в этот файл борку Python 3.6 со страницы github.com/docker-library/python/blob/master/3.6/alpine3.7/Dockerfile
не забыв удалить или закомментировать строку FROM alpine:3.7
И пробуем создать образ с Alpine 3.8 и Python на борту:
Результаты первого шага установка только Python (docker images —all):
- Debian 9 / 513 MB
- Fedora 28 / 387 MB
- Alpine 3.8 / 82.2 MB
Шаг 2. Установка cython и tornado
Начинаем добавлять пакеты pip. Первым установим cython и tornado. Для Debian и Fedora пакеты ставятся без ошибок, а вот Alpine падает с ошибкой:
Придется гуглить и потом уже добавлять библиотеки сборки в Alpine, чтобы pip успешно собрал их из исходного текста. Затем запускать сборку докера снова, затем опять искать зависимости, читать форумы stackoverflow и issues в github и ждать и ждать и ждать.
Поскольку в следующих шагах мы начнём добавлять математические и графические библиотеки в наш образ runtime Python, и чтобы слишком не увеличивать текст данной статьи, я приведу финальные зависимости для Alpine linux:
- Debian 9 / 534 MB
- Fedora 28 / 407 MB
- Alpine 3.8 / 144 MB
Шаг 3. Добавляем математику numpy scipy
- Debian 9 / 763 MB
- Fedora 28 / 626 MB
- Alpine 3.8 / 404 MB MB
Шаг 4. Добавляем графический стек websocket-client pytest pandas bokeh pillow
- Debian 9 / 905 MB
- Fedora 28 / 760 MB
- Alpine 3.8 / 650 MB
В качестве бонуса, попробуем в Alpine 3.8 скомпилировать ещё не вышедший для докера Python 3.7.
Новая версия Python 3.7 представлена 27 июня 2018 года
Размер Alpine 3.8 с Python 3.7 с текущим списком пакетов pip 656 MB
Итоги
Python
- Debian 9 / больше в 6.24х / +430 Mb
- Fedora 28 / больше в 4,7х / +304 Mb
Python tornado cython
- Debian 9 / больше в 3,71х / +390 Mb
- Fedora 28 / больше в 2,82x / +263 Mb
Python tornado cython numpy scipy
- Debian 9 / больше в 1,88 раз / +359 Mb
- Fedora 28 / больше в 1.54 раз / +222 Mb
Python tornado cython numpy scipy websocket-client pytest pandas bokeh pillow
- Debian 9 / больше в 1,39 раз / +255 Mb
- Fedora 28 / больше в 1.16 раз / +110 Mb
При использовании пустого runtime Python, дистрибутив Alpine linux лидер по минимальному размеру. При увеличени количества библиотек pip до tornado+cython+numpy+scipy Alpine все ещё дает заметную экономию в размере на жёстком диске. Одако как только в пакетах появляются графические утилиты для работы с данными для Python, разница практически исчезает.
При большом количестве графических пакетов, оптимальнее выбрать дистрибутив Fedora, чем заниматься компиляцией пакетов в Alpine (компиляция может длиться 1-2 часа), и в результате получить экономию в один или два десятка процентов места на жёстком диске.
UPDATE1: Тестирование проводилось на Fedora Atomic Host: release 28 (Twenty Eight), Version: 2018.5
Источник