Fedora coreos что это
Getting Started with Fedora CoreOS
Introduction
Streams
Each stream has a canonical URL representing its current state in JSON format, known as «stream metadata». For example, the stream metadata URL for stable is: https://builds.coreos.fedoraproject.org/streams/stable.json
For automating Fedora CoreOS installations, it is expected that you will interact with stream metadata. While Fedora CoreOS does automatic in-place updates, it is generally a good practice to start provisioning new machines from the latest images.
For more information on using stream metadata, see Stream Metadata. For more about the available streams, see Update Streams.
Provisioning Philosophy
Fedora CoreOS does not have a separate install disk. Instead, every instance starts from a generic disk image which is customized on first boot via Ignition.
Each platform has specific logic to retrieve and apply the first boot configuration. For cloud deployments, Ignition gathers the configuration via user-data mechanisms. In the case of bare metal, Ignition can fetch its configuration from the disk or from a remote source.
For more information on configuration, refer to the documentation for Producing an Ignition File.
Quickstart
Booting on a cloud VM (AWS example)
New AWS instances can be directly created from the public FCOS images. You can find the latest AMI for each region from the download page.
If you are only interested in exploring FCOS without further customization, you can use a registered SSH key-pair for the default core user.
To test out FCOS this way you’ll need to run the aws ec2 run-instances command and provide some information to get the instance up and running. The following is an example command you can use:
You can find out the instance’s assigned IP by running aws ec2 describe-instances |
You now should be able to SSH into the instance using the associated IP address.
By design, cloud-init configuration and startup scripts are not supported on FCOS. Instead, it is recommended to encode any startup logic as systemd service units in the Ignition configuration. |
Booting on a local hypervisor (libvirt example)
Fetch the latest image suitable for the qemu platform using coreos-installer (or download and verify it from the web). You can use coreos-installer as a container, or on Fedora install it from the repos.
virt-install requires both the OS image and Ignition file to be specified as absolute paths. |
Exploring the OS
Once the VM has finished booting, its IP addresses will appear on the serial console. By design, there are no hard-coded default credentials.
If you set up an SSH key for the default core user, you can SSH into the VM and explore the OS:
Getting in touch
We recommend that all users subscribe to the low-volume coreos-status mailing list for operational notices related to Fedora CoreOS.
Bugs can be reported to the Fedora CoreOS Tracker.
For live questions, feel free to reach out on the #fedora-coreos IRC channel on Libera.Chat.
For doubts and longer discussions related to Fedora CoreOS, a forum and a mailing list are available.
All Fedora Documentation content available under CC BY-SA 4.0 or, when specifically noted, under another accepted free and open content license.
CoreOS — Linux для минималистичных кластеров. Коротко
Что такое CoreOS?
CoreOS — это операционная система на базе Linux для построения легко и гибко масштабируемых кластеров. CoreOS — минималистичный дистрибутив. Установочный ISO образ объемом всего в 136Мб, а в памяти на конечной машине после установки и запуска она займет всего 114Мб. CoreOS основан на ChromeOS, который в свою очередь базируется на Gentoo.
Фактически, CoreOS можно условно можно разделить на следующие части:
CoreOS умеет запускать службы systemd на нужных машинах кластера, следить за их состоянием, хранить их конфигурацию.
Systemd
В CoreOS используется обычный systemd, который сейчас можно встретить во многих дистрибутивах Linux. Это система локального управления Linux-службами.
Docker
О Docker уже не раз писали на Хабре. Если коротко и по-простому — Docker берет ядро хостовой операционной системы Linux, монтирует к нему указанный вами образ файловой системы и позволяет работать внутри этого образа как будто вы находитесь в виртуализованном окружении.
Обратите внимание, что Docker не использует виртуализацию. Для изоляции процессов используются cgroups и namespaces, что позволяет избавиться от довольно серьезного оверхеда, который дают такие инструменты как KVM. Конечно, Docker можно использовать и на Mac и на Windows, но в этом случае хостовая операционная система должна будет работать внутри VirtualBox или любой другой системы виртуализации, поскольку Docker для работы необходимо ядро Linux (см. Boot2Docker)
Etcd — распределенное Key-Value хранилище, которое запускается на каждой машине кластера CoreOS и обеспечивает общий доступ практически ко всем данным в масштабе всего кластера. Внутри etcd хранятся настройки служб, их текущие состояние, конфигурация самого кластера и т.д. Etcd позволяет хранить данные иерархически (хранилище древовидно), подписываться на изменения ключей или целых директорий, задавать для ключей и директорий ключей значения TTL (фактически, «экспирить» их), атомарно изменять или удалять ключи, упорядоченно хранить их (что позволяет реализовывать своеобразные очереди). Поскольку конфигурация сервисов, запущенных в масштабе кластера, хранится в etcd, узнать о запуске и остановке того или иного сервиса можно просто подписавшись на изменения соответствующих ключей в хранилище.
Etcd поддерживает REST HTTP интерфейс, поэтому для работы с ним достаточно curl. Из командной строки в CoreOS управляется с помощью утилиты etcdctl.
Fleet
Fleet — это «надстройка» над systemd, которая переносит управление службами с локальной машины на уровень кластера. Fleet хранит конфигурацию служб в виде юнитов systemd (в etcd), автоматически доставляет ее на локальные машины, запускает, перезапускает (при необходимости), останавливает службы на машинах кластера. Fleet умеет планировать запуск служб исходя из загруженности конкретных машин кластера. Ему можно сказать, что конкретную службу нужно запускать только на определенных машинах и т.д.
CoreOS — это очень просто
Для того, чтобы запустить службу hello в кластере CoreOS, нужно всего-навсего сделать следующее:
1. Зайти на любой из серверов кластера по SSH (они все равноправны)
2. Создать текстовый файл с описанием службы. Например, hello.service:
3. Выполнить следующие команды:
4. Все! Получив последнюю команду, fleet, поскольку мы не дали ему никаких инструкций на этот счет, опеределит наименее загруженную машину кластера, возьмет наш юнит-файл, передаст его на выбранную машину, поместит туда, где systemd хранит свои службы и попросит systemd его запустить. А после запуска будет мониторить состояние. Если машина, на которой исполнялась служба, неожиданно «упадет», fleet перезапустит нашу службу на другой машине.
Рассмотрим наш пример поподробнее.
Файл конфигурации службы:
Команды, которые необходимо выполнить:
Посмотреть состояние служб можно командой fleetctl list-unit-files (короткая сводка по всем службам) либо fleetctl status hello.service (подробная информация о службе).
Установка CoreOS
CoreOS можно установить различными способами. Но если вы решили поэкспериментировать, рекомендую установку через Vagrant.
1. Установите Git, VirtualBox, затем Vagrant последних версий.
1а. Либо выполните в какой-нибудь папке git clone github.com/coreos/coreos-vagrant.git && cd coreos-vagrant
1б. Либо, если Git вам скачивать не захотелось, распакуйте куда-нибудь вот это.
2. Зайдите в папку, переименуйте там файл user-data.sample в user-data, config.rb.sample в config.rb. Зайдите на discovery.etcd.io/new, скопируйте в буфер появившийся URL, раскомментируйте строчку с инструкцией discovery в user-data и замените там URL.
3. Зайдите в папку и выполните там vagrant up
4. Дождитесь скачивания базового образа.
5. Выполните vagrant ssh.
Ограничения, слабые стороны и неожиданности CoreOS
CoreOS не обеспечивает ничего, кроме того, что обеспечивает 🙂 Иными словами, «из коробки», она не умеет ничего, кроме того, что мы обсудили. И, если вы собираетесь строить кластеры на базе CoreOS, вы столкнетесь как минимум со следующими проблемами:
Пакетный менеджер и обновления
В CoreOS отсутствует пакетный менеджер. И какая-либо система сборки или установки дополнительного ПО тоже (если не считать wget и curl 🙂 ). В качестве альтернативы могу предложить использовать интегрированный toolbox контейнер Docker. Для его активации просто выполните /usr/bin/toolbox из командной строки. Будет запущен привилегированный контейнер с Fedora, где есть доступ к yum.
Обновления CoreOS выполняются для ОС целиком с помощью системы активных/пассивных разделов. Фактически, системных разделов в CoreOS два. Активен в каждый момент только один из них. Обновление всей ОС устанавливается на второй, после чего выполняется перезагрузка и смена активного раздела. Операционная система обновляется только целиком. Соответственно, достаточно легко можно выполнить откат к предыдущей версии ОС. Если вы, как и я ;), уже захотели заиметь пакетный менеджер в CoreOS из коробки, прочтите Developer Documentation.
Обнаружение служб
«Фишка» CoreOS в том, что она легко переносит службы между машинами кластера, самостоятельно останавливая и запуская их. Грубо говоря, это значит, что ваш веб-сервер, изначально запущенный на машине X, через пять минут может легко оказаться на машине Y, у которой совсем другой IP адрес во внутренней сети. Конечно, с помощью специальных инструкций для Fleet вы можете легко «приковать» сервис к конкретной машине, но… тогда зачем вам вообще CoreOS? 🙂 Это создает проблему разрешения IP адресов для ваших служб. В принципе, достаточно легко запросить etcd и узнать, на какой машине сейчас выполняется служба. Но совсем автоматически этого не произойдет. Service Discovery вопрос достаточно серьезный и для его решения предлагается огромное количество ПО, из которого мне наиболее импонирует SkyDNS. Использовать SkyDNS можно с помощью sidekick-юнитов.
Персистентность контейнеров и данные как таковые
Если вы заметили, CoreOS фактически строится вокруг stateless docker-контейнеров, которые легко перенести на другую машину и там запустить. Действительно, довольно-таки легко контейнеризировать скажем, nginx и php-fpm. Файлы конфигурации для них тоже можно распространять в виде контейнера. Даже исходный код вашего приложения можно распространять в виде data-volume (это docker-контейнер, который содержит только данные) и подключать к различным службам. А что прикажете делать с базами данных?
Выходов несколько. Во-первых, сервисы вроде Flocker, которые мигрируют контейнеры с данными вслед за контейнерами со службами, которые эти данные используют. Во-вторых, запускать СУБД-подобные сервисы в режиме кластера. NoSQL решения умеют это очень хорошо, реляционные — заметно хуже, но все равно это возможно. В-третьих, можно поднять в рамках кластера любую распределенную файловую систему вроде GlusterFS или Ceph. Однако, подобное решение нужно оценить в точки зрения быстродействия. Эти вопросы обсуждались здесь.
Заключение
CoreOS сейчас переживает, не побоюсь этих слов, взрывной рост. Как и Docker, в общем-то. Количество различных проектов для CoreOS увеличивается с каждым днем. Так что, если сейчас вам чего-то не хватает для решения конкретной задачи, завтра эта возможность уже может появиться.
В рамках проекта CoreOS сейчас развивается альтернативный стандарт контейнеризациии Rocket. Однако… пока, видимо, лучше использовать Docker. Тем более, что CoreOS не собирается в будущем отказываться от Docker.
Что почитать?
Разумеется, можно почитать документацию. Однако мне больше всего понравился цикл статей на Digital Ocean о CoreOS. Собственно говоря, на его основе и под его влиянием и была написана данная статья 🙂
ОС для контейнеров Fedora CoreOS продолжит развитие Fedora Atomic и Container Linux
На этой неделе состоялся анонс первой предварительной версии Fedora CoreOS — специальной редакции Linux-дистрибутива Fedora, предназначенной для запуска приложений в контейнерах. По факту новая система продолжила развитие двух других проектов: Fedora Atomic Host и CoreOS Container Linux.
Наработки компании CoreOS, появившейся в 2013 году и ставшей хорошо известной в среде DevOps-инженеров и других любителей Linux-контейнеров, перешли к Red Hat в результате поглощения, что случилось полтора года назад. В то же самое время у американского Linux-вендора уже не один год формировалось своё видение нового дивного контейнерного мира — и происходило это, в частности, в рамках Project Atomic (о результатах его деятельности мы писали, например, здесь).
Появление Fedora CoreOS подтвердило намерения Red Hat объединить лучшее из собственных и приобретённых наработок в виде одного дистрибутива, призванного стать стандартом для развёртывания и запуска приложений в контейнерах. Как сообщается в анонсе проекта, он «сочетает инструменты provisioning’а, модель автоматических обновлений и философию Container Linux [от CoreOS] и технологию пакетирования, поддержку [стандарта] OCI, а также безопасность от SELinux из Atomic Host».
Среди основных фич Fedora CoreOS на данный момент называются:
Fedora CoreOS предназначен для использования в production, но это не относится к текущей предварительной версии. Ожидается, что систему объявят стабильной через полгода. Её предшественник в лице Fedora Atomic Host будет поддерживаться до конца жизни Fedora 29 (т.е. по конец ноября), и всем его пользователям рекомендуется мигрировать на Fedora CoreOS.
Образы для загрузки доступны здесь, а быстрая инструкция по запуску — здесь.
Prerequisites for the tutorials
The following tutorials are focused on helping you get started with Fedora CoreOS by learning how to automatically configure (or provision) an instance on first boot. Each tutorial has its roots in the previous one thus it is recommended to follow them sequentially.
If you don’t know what Fedora CoreOS is, you can refer to the FAQ for more information.
If you need any help or need to ask any questions while going through those tutorials, please join the IRC channel, or join our discussion board. If you find any issue in the tutorial, please report them in the fedora-coreos-docs issue tracker. |
You should start with the setup instructions from this page as they must be completed first to be able to follow the tutorials.
Enabling autologin and custom hostname: In this tutorial, you will write your first Ignition config and start a Fedora CoreOS instance with it.
Starting a service on first boot: In this tutorial, you will learn how to start a custom script via a systemd unit on the first boot of a Fedora CoreOS instance.
SSH access and starting containers: In this tutorial, you will learn how to start a container at first boot with podman.
Launching a user-level systemd unit on boot: There are times when it’s helpful to launch a user-level systemd unit without having to log in. This tutorial demonstrates creating a user-level systemd unit that launches on boot.
Testing Fedora CoreOS updates: In this tutorial, you will learn how automatic updates are handled in Fedora CoreOS and how to rollback in case of failures.
Virtualization with libvirt
For instructions to setup libvirt and KVM you may refer to the Getting started with virtualization guide from Fedora. Although this setup guide is focused on Fedora, the tutorials should work on any distribution with libvirt installed and running.
CoreOS tools
For the tutorials, we will need the following tools:
Butane: To generate Ignition configuration from Butane config files.
coreos-installer : To download the latest Fedora CoreOS QCOW2 image.
ignition-validate : To validate Ignition configuration files.
To keep all configurations files and Fedora CoreOS images in the same place, we will create a new directory to work from:
Setup with podman or docker
All of the tools required to work with Fedora CoreOS are available from containers hosted on quay.io:
To make it simpler to type, you may add the following aliases to your shell configuration:
You can then use coreos-installer to download the latest stable image with:
To make the tutorial simpler, you should rename the image that we have just downloaded to a shorter name:
You are now ready to proceed with the first tutorial.
Installing via Fedora packages
To make the tutorial simpler, you should rename the image that we have just downloaded to a shorter name:
You are now ready to proceed with the first tutorial.
Manual download
If none of the previous solutions work for you, you can still manually download Fedora CoreOS from getfedora.org with:
Once the archive has been downloaded, make sure to verify its integrity by following the instructions available by clicking on the Verify signature & SHA256 button. You will have to download the checksum file, the signature and Fedora GPG keys to verify your download:
Once you have verified the archive, you can extract it with:
To make the tutorial simpler, you should rename the image that we have just downloaded to a shorter name:
You should then download the latest Butane and ignition-validate releases from GitHub:
You may then setup aliases for butane and ignition-validate :
You are now ready to proceed with the first tutorial.
All Fedora Documentation content available under CC BY-SA 4.0 or, when specifically noted, under another accepted free and open content license.
Getting started with Fedora CoreOS
Introduce the different Fedora Linux editions
Use BespokeSynth on Fedora Linux
Use Diffoscope in packager workflows
This has been called the age of DevOps, and operating systems seem to be getting a little bit less attention than tools are. However, this doesn’t mean that there has been no innovation in operating systems. [Edit: The diversity of offerings from the plethora of distributions based on the Linux kernel is a fine example of this.] Fedora CoreOS has a specific philosophy of what an operating system should be in this age of DevOps.
Fedora CoreOS’ philosophy
Fedora CoreOS (FCOS) came from the merging of CoreOS Container Linux and Fedora Atomic Host. It is a minimal and monolithic OS focused on running containerized applications. Security being a first class citizen, FCOS provides automatic updates and comes with SELinux hardening.
Getting Started
For this example let’s use the stable stream and a QEMU base image that we can run as a virtual machine. You can use coreos-installer to download that image.
Create a configuration
To customize a FCOS system, you need to provide a configuration file that will be used by Ignition to provision the system. You may use this file to configure things like creating a user, adding a trusted SSH key, enabling systemd services, and more.
The following configuration creates a ‘core’ user and adds an SSH key to the authorized_keys file. It is also creating a systemd service that uses podman to run a simple hello world container.
After adding your SSH key in the configuration save it as config.yaml. Next use the Fedora CoreOS Config Transpiler (fcct) tool to convert this YAML configuration into a valid Ignition configuration (JSON format).
Install fcct directly from Fedora’s repositories or get the binary from GitHub.
Install and run Fedora CoreOS
To run the image, you can use the libvirt stack. To install it on a Fedora system using the dnf package manager
Now let’s create and run a Fedora CoreOS virtual machine
Once the installation is successful, some information is displayed and a login prompt is provided.
The Ignition configuration file did not provide any password for the core user, therefore it is not possible to login directly via the console. (Though, it is possible to configure a password for users via Ignition configuration.)
Use Ctrl + ] key combination to exit the virtual machine’s console. Then check if the hello.service is running.
Using the preconfigured SSH key, you can also access the VM and inspect the services running on it.
zincati, rpm-ostree and automatic updates
The zincati service drives rpm-ostreed with automatic updates.
Check which version of Fedora CoreOS is currently running on the VM, and check if Zincati has found an update.
After the restart, let’s remote login once more to check the new version of Fedora CoreOS.
rpm-ostree status now shows 2 versions of Fedora CoreOS, the one that came in the QEMU image, and the latest one received from the update. By having these 2 versions available, it is possible to rollback to the previous version using the rpm-ostree rollback command.
Finally, you can make sure that the hello service is still running and serving content.
Deleting the Virtual Machine
To clean up afterwards, the following commands will delete the VM and associated storage.
Conclusion
Fedora CoreOS provides a solid and secure operating system tailored to run applications in containers. It excels in a DevOps environment which encourages the hosts to be provisioned using declarative configuration files. Automatic updates and the ability to rollback to a previous version of the OS, bring a peace of mind during the operation of a service.
Learn more about Fedora CoreOS by following the tutorials available in the project’s documentation.