Sure! Below is a comprehensive step-by-step Proof of Concept (PoC) tutorial that integrates Docker, Python (with a virtual environment), the Faker API for data simulation, and Apache Airflow orchestrated using Docker Compose on an Ubuntu Linux distribution.
Table of Contents
- Prerequisites
- Step 1: Set Up Your Ubuntu Environment
- Step 2: Install Docker and Docker Compose
- Step 3: Set Up Python Virtual Environment
- Step 4: Create a Python Script Using Faker
- Step 5: Set Up Apache Airflow with Docker Compose
- Step 6: Create an Airflow DAG to Execute the Python Script
- Step 7: Run the Entire Setup Using Docker Compose
- Step 8: Verify the Setup
- Conclusion
Prerequisites
Before starting, ensure you have:
- A machine running Ubuntu (preferably 20.04 LTS or later).
- User with sudo privileges.
- Basic knowledge of terminal commands, Python, and Docker.
Step 1: Set Up Your Ubuntu Environment
-
Update and Upgrade Packages
sudo apt update && sudo apt upgrade -y
-
Install Essential Packages
sudo apt install -y build-essential libssl-dev libffi-dev python3-dev python3-pip
Step 2: Install Docker and Docker Compose
Install Docker
-
Remove Old Versions
sudo apt remove docker docker-engine docker.io containerd runc
-
Set Up Repository
sudo apt update
sudo apt install -y \
ca-certificates \
curl \
gnupg \
lsb-release
-
Add Docker’s Official GPG Key
sudo mkdir -m 0755 -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
-
Set Up the Stable Repository
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
-
Install Docker Engine
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
-
Verify Docker Installation
sudo docker run hello-world
Install Docker Compose
Docker Compose might already be installed with Docker. Verify:
docker compose version
If not installed, install using:
sudo curl -L "https://github.com/docker/compose/releases/download/2.20.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version
(Replace 2.20.2 with the latest version if necessary.)
Step 3: Set Up Python Virtual Environment
-
Install virtualenv
sudo pip3 install virtualenv
-
Create a Project Directory
mkdir ~/docker-airflow-faker-poc
cd ~/docker-airflow-faker-poc
-
Set Up Virtual Environment
python3 -m venv venv
source venv/bin/activate
-
Upgrade pip
pip install --upgrade pip
Step 4: Create a Python Script Using Faker
-
Install Faker
pip install faker
-
Create a Python Script
Create a file named generate_data.py:
touch generate_data.py
chmod +x generate_data.py
-
Add the Following Code to generate_data.py
from faker import Faker
import json
import datetime
def generate_user():
fake = Faker()
user = {
"name": fake.name(),
"address": fake.address(),
"email": fake.email(),
"created_at": datetime.datetime.now().isoformat()
}
return user
if __name__ == "__main__":
user_data = generate_user()
with open("user_data.json", "w") as f:
json.dump(user_data, f, indent=4)
print("User data generated and saved to user_data.json")
This script generates a fake user and saves it to user_data.json.
Step 5: Set Up Apache Airflow with Docker Compose
-
Create a docker-compose.yaml File
In your project directory (~/docker-airflow-faker-poc), create docker-compose.yaml:
touch docker-compose.yaml
-
Add the Following Configuration to docker-compose.yaml
version: '3'
services:
postgres:
image: postgres:13
environment:
POSTGRES_USER: airflow
POSTGRES_PASSWORD: airflow
POSTGRES_DB: airflow
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U airflow"]
interval: 10s
retries: 5
webserver:
image: apache/airflow:2.6.3
depends_on:
postgres:
condition: service_healthy
environment:
AIRFLOW__CORE__EXECUTOR: LocalExecutor
AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow
AIRFLOW__CORE__FERNET_KEY: ''
AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true'
AIRFLOW__CORE__LOAD_EXAMPLES: 'false'
volumes:
- ./dags:/opt/airflow/dags
- ./scripts:/opt/airflow/scripts
- ./logs:/opt/airflow/logs
ports:
- "8080:8080"
command: webserver
scheduler:
image: apache/airflow:2.6.3
depends_on:
- webserver
environment:
AIRFLOW__CORE__EXECUTOR: LocalExecutor
AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow
volumes:
- ./dags:/opt/airflow/dags
- ./scripts:/opt/airflow/scripts
- ./logs:/opt/airflow/logs
command: scheduler
volumes:
postgres_data:
Explanation:
-
Services:
- postgres: PostgreSQL database for Airflow metadata.
- webserver: Airflow web interface.
- scheduler: Airflow scheduler.
-
Volumes:
- Persist PostgreSQL data.
- Mount
dags, scripts, and logs directories.
-
Create Necessary Directories
mkdir dags scripts logs
-
Install Airflow Dependencies
While the Airflow Docker image comes pre-installed with necessary dependencies, ensure any custom scripts you add have the required packages. Since generate_data.py uses faker, ensure faker is available in the Airflow environment.
Step 6: Create an Airflow DAG to Execute the Python Script
-
Create a DAG File
In the dags directory, create generate_data_dag.py:
touch dags/generate_data_dag.py
-
Add the Following Code to generate_data_dag.py
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.utils.dates import days_ago
import os
default_args = {
'owner': 'airflow',
}
with DAG(
'generate_fake_data',
default_args=default_args,
description='A simple DAG to generate fake user data using Faker',
schedule_interval='@daily',
start_date=days_ago(1),
tags=['example'],
) as dag:
generate_data = BashOperator(
task_id='generate_data',
bash_command='python /opt/airflow/scripts/generate_data.py',
)
generate_data
Explanation:
- DAG: Defined to run daily, starting from the day before.
- Task (
generate_data): Executes the Python script generate_data.py.
-
Place the Python Script in scripts Directory
Move the previously created generate_data.py to the scripts directory:
mv generate_data.py scripts/
-
Ensure Executability and Dependencies
Since Airflow runs inside Docker containers, ensure the script has necessary permissions and dependencies.
-
Optionally, Create a Dockerfile to Extend Airflow Image:
To include faker in Airflow's environment, create a custom Docker image.
touch Dockerfile
Add the following content:
FROM apache/airflow:2.6.3
USER root
RUN pip install faker
USER airflow
-
Modify docker-compose.yaml to Use the Custom Image:
Update the webserver and scheduler services to build from the Dockerfile:
services:
webserver:
build: .
# ... rest remains the same
scheduler:
build: .
# ... rest remains the same
-
Note: Building the Docker image ensures is available within Airflow containers.
Step 7: Run the Entire Setup Using Docker Compose
-
Initialize the Airflow Database
Before starting Airflow, initialize the database:
docker-compose up airflow-init
This step might require adding an airflow-init service or adjusting commands. Alternatively, use provided entrypoints.
Simplified Approach:
Instead of manually initializing, use the official Airflow Docker Compose setup. However, to keep it simple, proceed to start all services.
-
Build and Start Services
docker-compose up -d --build
Explanation:
-d: Runs containers in detached mode.
--build: Builds images before starting containers.
-
Verify Containers are Running
docker-compose ps
You should see postgres, webserver, and scheduler containers running.
Step 8: Verify the Setup
-
Access the Airflow Web Interface
-
Open your browser and navigate to http://localhost:8080.
-
Default credentials are often:
Username: airflow
Password: airflow
If not set, you might need to set them or check Airflow logs for default credentials.
-
Check the DAG
- In the Airflow UI, locate the
generate_fake_data DAG.
- If it's paused, unpause it by toggling the switch.
- Trigger the DAG manually or wait for the scheduled run.
-
Monitor the Task
- Click on the DAG to view task instances.
- Check the logs of the
generate_data task to ensure it executed successfully.
-
Verify Generated Data
-
The script writes user_data.json to the Airflow container's filesystem.
-
To view the file, you can exec into the webserver container:
docker-compose exec webserver /bin/bash
-
Navigate to the directory and view the file:
cd /opt/airflow
cat user_data.json
-
You should see a JSON file with fake user data.
Additional Enhancements (Optional)
Persisting Generated Data
To persist user_data.json outside the Docker container:
-
Modify docker-compose.yaml to Mount a Volume
services:
webserver:
# ... existing configurations
volumes:
- ./dags:/opt/airflow/dags
- ./scripts:/opt/airflow/scripts
- ./logs:/opt/airflow/logs
- ./data:/opt/airflow/data # New volume
-
Modify generate_data.py to Save to /opt/airflow/data
# ... existing imports
DATA_DIR = "/opt/airflow/data"
os.makedirs(DATA_DIR, exist_ok=True)
# ... inside main
with open(os.path.join(DATA_DIR, "user_data.json"), "w") as f:
json.dump(user_data, f, indent=4)
-
Update the DAG Accordingly
No changes needed if the script handles the path.
Conclusion
This Proof of Concept demonstrates how to integrate Docker, Python (with a virtual environment), the Faker API, and Apache Airflow using Docker Compose on an Ubuntu system. The setup allows you to:
- Generate simulated data using Python and Faker.
- Orchestrate the data generation task using Airflow.
- Manage the entire stack using Docker Compose for ease of deployment and scalability.
This foundation can be expanded to include more complex workflows, additional services, and integration with other data pipelines as needed.
Feel free to customize and expand upon this setup to suit your specific requirements!