By Aviator Ifeanyichukwu
Apache Airflow is a tool that helps you manage and schedule data pipelines. According to the documentation, it lets you «programmatically author, schedule, and monitor workflows.»
Airflow is a crucial tool for data engineers and scientists. In this article, I’ll show you how to install it on Windows without Docker.
Although it’s recommended to run Airflow with Docker, this method works for low-memory machines that are unable to run Docker.
Prerequisites:
This article assumes that you’re familiar with using the command line and can set up your development environment as directed.
Requirements:
You need Python 3.8 or higher, Windows 10 or higher, and the Windows Subsystem for Linux (WSL2) to follow this tutorial.
What is Windows Subsystem for Linux (WSL2)?
WSL2 allows you to run Linux commands and programs on a Windows operating system.
It provides a Linux-compatible environment that runs natively on Windows, enabling users to use Linux command-line tools and utilities on a Windows machine.
You can read more here to install WSL2 on your machine.
With Python and WSL2 installed and activated on your machine, launch the terminal by searching for Ubuntu from the start menu.
Step 1: Set Up the Virtual Environment
To work with Airflow on Windows, you need to set up a virtual environment. To do this, you’ll need to install the virtualenv package.
Note: Make sure you are at the root of the terminal by typing:
cd ~
pip install virtualenv
Create the virtual environment like this:
virtualenv airflow_env
And then activate the environment:
source airflow_env/bin/activate
Step 2: Set Up the Airflow Directory
Create a folder named airflow. Mine will be located at c/Users/[Username]. You can put yours wherever you prefer.
If you do not know how to navigate the terminal, you can follow the steps in the image below:
Create an Airflow directory from the terminal
Now that you have created this folder, you have to set it as an environment variable. Open a .bashrc script from the terminal with the command:
nano ~/.bashrc
Then write the following:
AIRFLOW_HOME=/c/Users/[YourUsername]/airflow
Setup Airflow directory path as an environment variable
Press ctrl s and ctrl x to exit the nano editor.
This part of the Airflow directory will be permanently saved as an environment variable. Anytime you open a new terminal, you can recover the value of the variable by typing:
cd $AIRFLOW_HOME
Navigate to Airflow directory using the environment variable
With the virtual environment still active and the current directory pointing to the created Airflow folder, install Apache Airflow:
pip install apache-airflow
Initialize the database:
airflow db init
Create a folder named dags inside the airflow folder. This will be used to store all Airflow scripts.
View files and folders generated by Airflow db init
Step 4: Create an Airflow User
When airflow is newly installed, you’ll need to create a user. This user will be used to login into the Airflow UI and perform some admin functions.
airflow users create --username admin –password admin –firstname admin –lastname admin –role Admin –email youremail@email.com
Check the created user:
airflow users list
Create an Airflow user and list the created user
Step 5: Run the Webserver
Run the scheduler with this command:
airflow scheduler
Launch another terminal, activate the airflow virtual environment, cd to $AIRFLOW_HOME, and run the webserver:
airflow webserver
If the default port 8080 is in use, change the port by typing:
airflow webserver –port <port number>
Log in to the UI using the username created earlier with «airflow users create».
In the UI, you can view pre-created DAGs that come with Airflow by default.
How to Create the first DAG
A DAG is a Python script for organizing and managing tasks in a workflow.
To create a DAG, navigate into the dags folder created inside the $AIRFLOW_HOME directory. Create a file named «hello_world_dag.py». Use VS Code if it’s available.
Enter the code from the image below, and save it:
Example DAG script in VS Code editor
Go to the Airflow UI and search for hello_world_dag. If it does not show up, try refreshing your browser.
That’s it. This completes the installation of Apache Airflow on Windows.
Wrapping Up
This guide covered how to install Apache Airflow on a Windows machine without Docker and how to write a DAG script.
I do hope the steps outlined above helped you install airflow on your Windows machine without Docker.
In subsequent articles, you will learn about Apache Airflow concepts and components.
Follow me on Twitter or LinkedIn for more Analytics Engineering content.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Преамбула: волею судьбы из мира академической науки (медицины) я попала в мир информационных технологий, где мне приходится использовать свои знания о методологии построения эксперимента и стратегиях анализа экспериментальных данных, однако, применять новый для меня стек технологий. В процессе освоения этих технологий я сталкиваюсь с рядом трудностей, которые пока, к счастью, удается преодолевать. Возможно, этот пост будет полезен тем, кто также только начинает работу с проектами Apache.
Итак, к сути. Вдохновившись статьей Юрия Емельянова о возможностях Apache Airflow в области автоматизации аналитических процедур, мне захотелось начать использовать предлагаемый набор библиотек в своей работе. Тем, кто еще совсем не знаком с Apache Airflow, может быть интересна небольшая обзорная статья на сайте Национальной библиотеки им. Н. Э. Баумана.
Поскольку обычные инструкции для запуска Airflow, судя по всему, не применяются в среде Windows, а использовать для решения данной задачи докер в моем случае было бы избыточно, я начала поиск других решений. К счастью для меня, я оказалась не первой на этом пути, поэтому мне удалось найти замечательную видео-инструкцию по установке Apache Airflow в Windows 10 без использования докера. Но, как это часто и бывает, при выполнении рекомендуемых шагов, возникают трудности, и, полагаю, не только у меня. Поэтому я хотела бы рассказать о своем опыте установки Apache Airflow, возможно кому-то это сэкономит немного времени.
Пройдемся по шагам инструкции (спойлер — 5-го шага все шло прекрасно):
1. Установка подсистемы Windows для Linux для последующей установки дистрибутивов Linux
Это меньшая из проблем, как говорится:
Панель управления → Программы → Программы и компоненты → Включение и отключение компонентов Windows → Подсистема Windows для Linux
2. Установка дистрибутива Linux по выбору
Я воспользовалась приложением Ubuntu.
3. Установка и апдейт pip
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
4. Установка Apache Airflow
export SLUGIFY_USES_TEXT_UNIDECODE=yes
pip install apache-airflow
5. Инициализация базы данных
И вот именно здесь начались мои маленькие трудности. Инструкция предписывает ввести команду airflow initdb
и перейти к следующему шагу. Однако я неизменно получала ответ airflow: command not found
. Логично предположить, что возникли трудности на этапе установки Apache Airflow и просто нет нужных файлов. Удостоверившись, что все там где и должно быть, я решила попробовать указать полный путь до файла airflow (выглядеть должно так: Полный/путь/до/файла/airflow initdb
). Но чуда не произошло и ответ был тем же airflow: command not found
. Я попробовала использовать относительный путь к файлу (./.local/bin/airflow initdb
), что привело к появлению новой ошибки ModuleNotFoundError: No module named json'
, которую можно преодолеть, обновив библиотеку werkzeug (в моем случае до версии 0.15.4):
pip install werkzeug==0.15.4
Подробнее о werkzeug можно почитать здесь.
После этой нехитрой манипуляции команда ./.local/bin/airflow initdb
была выполнена успешно.
6. Запуск сервера Airflow
На этом сложности с обращением к airflow еще не завершились. Запуск команды ./.local/bin/airflow webserver -p 8080
привел к ошибке No such file or directory
. Вероятно, опытный пользователь Ubuntu сразу бы попробовал преодолеть такие трудности с обращением к файлу, применив команду export PATH=$PATH:~/.local/bin/
(то есть, добавив к существующему пути поиска исполняемых файлов, определяемому переменной PATH каталог /.local/bin/), но этот пост предназначен для тех, кто преимущественно работает с Windows и, возможно, не считает такое решение очевидным.
После описанной выше манипуляции команда ./.local/bin/airflow webserver -p 8080
была успешно выполнена.
7. URL: localhost:8080/
Если все прошло удачно на предыдущих этапах, то вы готовы покорять аналитические вершины.
Надеюсь, описанный выше опыт установки Apache Airflow на Windows 10 будет полезен начинающим пользователям и ускорит их вхождение во вселенную современных инструментов аналитики.
В следующий раз хотелось бы продолжить тему и рассказать об опыте использования Apache Airflow в сфере анализа поведения пользователей мобильных приложений.
В этой части покажу, как развернуть Airflow – замечательное ПО для автоматизации почти всего на Python. Мы будем использовать в качестве базы Windows 10 + Linux WSL (“Windows Subsystem for Linux” – подсистема Linux на Windows).
Это статья из цикла “5 ETL для зоопарка ботов”. В нем я пошагово разбираю, как наладить потоки данных из разных библиотек и конструкторов ботов на разных языках и стеках. В основе лежат Python и его библиотеки.
Вот предыдущие статьи цикла, подводящие к текущей:
- Анонс цикла с перечнем технологий
- Настройка потока логов «Из Dialogflow в BigQuery»
- Python для аналитики ad hoc из BigQuery
Конечно, можно использовать и официальный Docker-контейнер, чтобы точно воспроизводить среду при последующих развертываниях, однако я остановлюсь именно на таком стеке, поскольку это моя реальность, да и много сущностей разворачивать не приходится. Возможно, кому-то да пригодится такой стек.
Для простоты обойдусь без развертки образа на виртуальном частном сервере, разборками с имеющейся и требуемой оперативной памятью и, конечно, падениями контейнеров, до причин которых еще надо уметь докопаться.
Установка Linux WSL
Некоторые важнейшие компоненты Airflow под Win не адаптированы. Поэтому нам понадобится Linux. откроем командную строку Windows 10 как администратор и наберем:
Процесс скачивания дистрибутива Ubuntu начался:
Чтобы пакет ОС “развернулся”, перезагрузим Windows. Сразу после авторизации окно командной строки откроется само и установка Linux продолжится. Спустя несколько минут потребуется ввести имя пользователя и пароль:
На этом установку подсистемы мы завершаем. Теперь Ubuntu можно запустить из меню “Пуск”:
Прежде чем устанавливать программу, нам потребуется настроить виртуальную среду – некий прообраз контейнера Docker, который позволит воспроизвести на любой другой машине те же условия с версиями языка и пакетов. Установим библиотеку для создания таких образов:
Создадим виртуальное окружение для изоляции проекта от остальных событий и мест в Linux:
virtualenv airflow_env
source airflow_env/bin/activate
Теперь настало время настроить проект. Для этого создадим отдельную папку и зайдем в нее:
Установим airflow:
pip install apache-airflow
Обязательное условие для запуска утилиты – работающая база данных. Мой проект использует BigQuery API, но использовать следующую команду все равно придется:
Поскольку у Airflow есть и браузерный UI с авторизацией, то создадим пользователя-админа:
airflow users create --username admin -password admin -firstname admin -lastname admin -role Admin -email youremail@email.com
Запустим веб-сервер с экземпляром Airflow:
Так вы сможете поиграться с этой прекрасной программой в браузере, просто перейдя по ссылке http://localhost:8080 (в моем случае 8081 – настроила нестандартный порт, пока разбиралась с мануалом по установке).
Спустя примерно час в списке DAG’ов (Directed Acyclic Graph) появятся обучающие скрипты (их Airflow подтянет самостоятельно). Прежде чем мы перейти к настройке своего кода, можно “провалиться” в парочку (например, ‘example_bash_operator’) и посмотреть «питоническое» содержимое во вкладке ‘Code’:
Заключение
Конечно, на этом я не остановлюсь, ибо Airflow вызывает у меня любовь. Появилась она, когда отслеживать вручную многочисленные скрипты на crontab (утилита Linux, позволяющая запустить код по расписанию) стало неудобно. Прописывать руками все то, что умеет Airflow, бессмысленно: там и аналитика исполняемости, и дополнительная защита от взлома, и безконсольный доступ к логам, и даже плагины.
Мое пожелание крупным российским компаниям поскорее становиться профессиональнее в вопросах автоматической отчетности, и внедрять такие opensource-решения.
А если вы захотели прокачаться как дата-аналитик, рекомендую курс “Аналитика на Python”.
airflow_base_RU
Установка Apache Airflow на Windows 10 и простые первые даги DAG’s
Для установки airflow на windows 10 необходимо сначала установить подсистему Windows для Linux (Windows subsystem for Linux — WSL), т.к. airflow не поддерживает windows((
Шаг 1.
Изначально компонент WSL отключен. Чтобы его включить, вам необходимо зайти в Пуск -> Панель управления -> Программы и компоненты -> Включение и отключение компонентов windows , активировать галочку -> Подсистема Windows для Linux (Windows Subsystem for Linux) , нажать кнопку ОК, и перезагрузить компьютер.
Шаг 2.
Качаем и устанавливаем любой понравившийся дистрибьютив.
Все готово к началу установки.
Шаг 3.
Сама установка описана в официальной документации и разбита на следующие действия:
- сначала в командной строке вводим
wsl
для доступа к установленной подсистеме; - затем непостредственно установка —
pip install apache-airflow
; - если «по-хорошему» не прошло, то выполняем следующий набор команд для выбора и установки определенной версии:
export AIRFLOW_HOME=~/airflow
source ~/.bashrc
AIRFLOW_VERSION=2.2.3
PYTHON_VERSION="$(python3 --version | cut -d " " -f 2 | cut -d "." -f 1-2)"
CONSTRAINT_URL="https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt"
pip3 install "apache-airflow==${AIRFLOW_VERSION}" --constraint "${CONSTRAINT_URL}"
export PATH=$PATH:~/.local/bin
source ~/.bashrc
- инициализация базы данных, по умолчанию sqlite —
airflow db init
; - создание пользователя —
airflow users create \ --username admin \ --firstname Peter \ --lastname Parker \ --role Admin \ --email spiderman@superhero.org
- запуск локального сервера —
airflow webserver --port 8080
- запуск шедулера в новом окне —
airflow scheduler
Если все сделано верно, то при посещении localhost:8080 и после ввода данных пользователя вам будут доступны для ознакомления с функциональностью стандартные даги, их уже можно покрутить/позапускать и посмотреть на результаты.
П.С.
По умолчанию создается домашняя папка AIRFLOW_HOME=~/airflow, ее можно сменить export AIRFLOW_HOME='ваш путь'
. В папку airflow/dags необходимо будет поместить все ваши новые даги для последующей с ними работы.
Для того чтобы получить доступ к папкам подсистемы проделаем следующее cmd -> wsl -> cd ~/ -> explorer.exe .
Apache Airflow is a powerful tool for managing and automating workflows and can be installed on multiple operating systems. It is one of the most trusted platforms for orchestrating workflows and is widely used and recommended by top data engineers.
Apache Airflow provides many features, such as a proper visualization of the data pipelines and workflows, the status of the workflows, the data logs, and codes in quite a detail.
This article provides a clear, step-by-step guide to help you install Airflow on your system, no matter what platform you are using
What is Apache Airflow?
Apache Airflow is a workflow engine that helps in scheduling and running data pipelines that are complex. Airflow makes sure that all the steps of the data pipeline get executed in the predefined order and all the tasks get the resources based on the requirement.
How to Install Airflow?
- Installing Airflow is a difficult task, but the benefits it provides sometimes outweigh the difficulties faced by data professionals since it is mostly a one-time process.
Method 1: Installing Airflow in Linux
The installation of Airflow is four steps.
- Step 1: Installing Ubuntu
- Step 2: Installing pip
- Step 3: Install Airflow Dependencies
- Step 4: Install Airflow
Simplify Data Analysis with Hevo’s No-code Data Pipeline
As you learn about Airflow, it’s important to know about the best platforms for data integration as well. Hevo Data, a No-code Data Pipeline platform, helps to replicate data from any data source such as Databases, SaaS applications, Cloud Storage, SDKs, and Streaming Services, and simplifies the ETL process.
It supports 150+ data sources (including 60+ free data sources) like Asana and is an easy 3-step process. With Hevo’s transformation feature, you can modify the data and make it into analysis-ready form.
Check out some of the cool features of Hevo:
- Completely Automated: Set up in minutes with minimal maintenance.
- Real-Time Data Transfer: Get analysis-ready data with zero delays.
- 24/5 Live Support: Round-the-clock support via chat, email, and calls.
- Schema Management: Automatic schema detection and mapping.
- Live Monitoring: Track data flow and status in real-time.
Get Started with Hevo for Free
Let us understand the steps in detail, to install airflow.
Step 1.1: Installing Ubuntu
Ubuntu is a Linux operating system. It provides a more controlled environment over all the functionalities of the system.
- Before installing Ubuntu, turn on the developer option on the windows system.
- Enable the subsystem for the Linux option located in Windows Features.
- Download the visual C++ module.
- Install Ubuntu from Microsoft Store or use an ISO file. start the installation process
- A terminal will open where you need to enter your username and password. The terminal doesn’t show the password that you type in.
Ubuntu Installing, this may take a few minutes... Please create a default UNIX user account. The username does not need to match your Windows username. For more information visit: https://aka.ms/wslusers Enter new UNIX username: bull87
- Bash command can be used if you closed the terminal after the last step and reopen it. Bash command helps to communicate with the computer.
C:Usersjacks>bash To run a command as administrator (user "root"), use "sudo <command>". See "man sudo root" for details.
bull87@DESKTOP-G50VTBF:/mnt/c/Users/jacks
Step 1.2: Installing PIP
Pip is a tool that manages and is designed to install the packages that are written for python and written in python. Pip is required to download Apache Airflow. Run through the following code commands to implement this step:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-setuptools
sudo apt install python3-pip
sudo -H pip3python install --upgrade pip
Step 1.3: Install Airflow Dependencies
For airflow to work properly you need to install all its dependencies. Without dependencies Airflow cannot function to its potential i.e, there would be a lot of missing features and may even give bugs. To avoid it run the following commands and install all dependencies.
sudo apt-get install libmysqlclient-dev
sudo apt-get install libssl-dev
sudo apt-get install libkrb5-dev
Airflow uses SQLite as its default database
Step 1.4: Install Airflow
Run the following command to finally install airflow on your system.
export AIRFLOW_HOME=~/airflowpip3 install apache-airflowpip3 install typing_extensions# initialize the database
airflow initdb
# start the web server, default port is 8080
airflow webserver -p 8080# start the scheduler. I recommend opening up a separate terminal #window for this step
airflow scheduler
# visit localhost:8080 in the browser and enable the example dag in the home page
After you execute the following commands, the process to install airflow on your system is complete. This allows you to access and utilize the complete potential of the airflow tool.
Method 2: Installing Airflow for Windows PC
Here, we are going to install airflow for Windows PC. So there are certain prerequisites for it, such as:
- Docker Desktop
- Visual Studio
Step 1 – Save the .YAML file in a separate folder. It is needed to start the Apache Airflow.
Step 2 – Create a .env file to define configuration variables. For this, open Visual Studio code and open your .yaml file containing the folder in this. After this, create a new file with the extension .env. Enter Airflow_Image_name and Airflow_UID into it and save it.
Step 3 – Pick up the docker-compose file. To do so, go to the new terminal and pass the argument.
Docker-compose up-d
Step 4 – You can execute it, and it starts pulling all the files and Airflow services.
Step 5 – This shows that Apache airflow has been successfully installed
Step 6 – Go to your local host 8080, to access the login page of airflow. To create an admin username and password, copy the following command and paste in Visual Studio
docker -compose run airflow-worker airflow users create --role Admin --
username admin --email admin --firstname admin --lastname admin --password
admin
Step 7 – Now enter the credentials to log in to Apache airflow
Thus, you have successfully set up Apache airflow in windows PC.
Other Methods to Install Airflow
Using Released Sources
- This is suitable if you want to build your software from sources and want to verify the integrity of the software.
- You will have to build, install, set, and handle all components of Airflow on your own.
Using PyPi
- It is useful when you want to install Airflow on the physical or virtual machine, and you are not familiar with docker and containers.
- This is only supported by pip through the constraint mechanism.
- You can use this method if you are familiar with Python programming and running custom deployment mechanism software.
Using Production Docker images
- This is useful if you are familiar with the docker stack and know how to build container images.
- If you understand how to install providers and dependencies from PyPI
- If you know how to create docker deployments and link multiple docker containers together.
Using Official Airflow Helm Chart
- This is helpful if you know how to manage infrastructure using Kubernetes and applications on Kubernetes using Helm Charts.
Using Managed Airflow Services
- This can be used when you want someone else to manage your Airflow account and are ready to pay for it.
Using 3rd party images, charts, deployments
- You can use this if you have tried other ways of installations and found them insufficient.
Overview of Apache Airflow Platform Workflow
- Apache Airflow is an open-source platform for properly monitoring, scheduling, and executing complex workflows. It is useful in creating workflow architecture.
- Airflow is one of the most powerful open source data pipeline platforms currently in the market. Airflow uses DAG ( Directed Acyclic Graphs) to structure and represent the workflows, where nodes of DAG represent the tasks.
- The ideology behind Airflow’s design is that all the data pipelines can be expressed as code. It soon became a platform where workflows can iterate quickly and utilize code-first platforms.
Features of Apache Airflow
- Ease of use: Deploying airflow is easy as it requires just a little bit of knowledge in python.
- Open Source: It is free to use, open-source platform that results in a lot of active users.
- Good Integrations: It has readily available integrations that allow working with platforms like Google Cloud, Amazon AWS, and many more.
- Standard Python for coding: Relatively little knowledge of python can help in creating complex workflows
- User Interface: Airflow’s UI helps in monitoring and managing the workflows. It also provides a view of the status of tasks.
- Dynamic: All the tasks of python can be performed in airflow since it is based on python itself.
- Highly Scalable: Airflow allows the execution of thousands of different tasks per day.
Integrate MySQL to Snowflake
Integrate BigQuery to Redshift
Integrate Shopify to BigQuery
Final Thoughts
- Airflow is one of the most powerful workflow management tools on the market. By utilizing its potential, companies can solve their problems and complete tasks on time with efficiency.
- This article gave a comprehensive guide on Airflow and then a step-by-step guide to installing Airflow in an easy manner. Airflow is a trusted source that a lot of companies use as it is an open-source platform.
- Creating pipelines, installing them on the system, and monitoring pipelines are all very difficult on Airflow as it is a completely coding platform that requires a lot of expertise to run properly. A platform that creates data pipelines with any code can solve this issue.
Sign up for a 14-day free trial and simplify your data integration process. Check out the pricing details to understand which plan fulfills all your business needs.
Frequently Asked Questions
1. How can I install Airflow?
Airflow can be installed using the command `pip install apache-Airflow` in your terminal. Make sure to set up a virtual environment first.
2. How do you install an Airflow worker?
To install an Airflow worker, use the command `pip install apache-Airflow[celery]` in your terminal and configure it as a Celery worker.
3. Is Airflow an ETL tool?
Yes, Airflow can be used as an ETL tool to orchestrate and automate data extraction, transformation, and loading workflows.
Arsalan is a research analyst at Hevo and a data science enthusiast with over two years of experience in the field. He completed his B.tech in computer science with a specialization in Artificial Intelligence and finds joy in sharing the knowledge acquired with data practitioners. His interest in data analysis and architecture drives him to write nearly a hundred articles on various topics related to the data industry.