{"id":25834687,"url":"https://github.com/nihilantropy/inception","last_synced_at":"2025-10-29T06:14:58.820Z","repository":{"id":266695138,"uuid":"899055554","full_name":"Nihilantropy/Inception","owner":"Nihilantropy","description":"This project aims to broaden your knowledge of system administration by using Docker. You will virtualize several Docker images, creating them in your new personal virtual machine.","archived":false,"fork":false,"pushed_at":"2025-01-17T16:59:30.000Z","size":51511,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-17T17:52:17.000Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Nihilantropy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-05T14:40:34.000Z","updated_at":"2025-01-17T16:59:31.000Z","dependencies_parsed_at":"2024-12-07T15:31:30.775Z","dependency_job_id":null,"html_url":"https://github.com/Nihilantropy/Inception","commit_stats":null,"previous_names":["nihilantropy/inception"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nihilantropy%2FInception","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nihilantropy%2FInception/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nihilantropy%2FInception/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nihilantropy%2FInception/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Nihilantropy","download_url":"https://codeload.github.com/Nihilantropy/Inception/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241300492,"owners_count":19940489,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-01T00:59:00.170Z","updated_at":"2025-10-29T06:14:53.800Z","avatar_url":"https://github.com/Nihilantropy.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Inception Art](images/inception-art.png)\n\n\u003c!--=====================================\n=           INTRODUCTION              =\n======================================--\u003e\n# Introduction to Inception 🚀\n\nA comprehensive guide to building a containerized web infrastructure.\n\n\u003c!--=====================================\n=         TABLE OF CONTENTS           =\n======================================--\u003e\n# Table of Contents 📚\n\n1. [Prerequisites](#prerequisites-)\n   - [System Requirements](#system-requirements)\n   - [Software Dependencies](#software-dependencies)\n   - [Environment Setup](#environment-setup)\n   - [Installation Steps](#installation-steps)\n\n2. [Introduction to Inception](#introduction-to-inception)\n   - [What is Inception?](#what-is-inception)\n   - [Project Goals](#project-goals-)\n   - [Architecture Overview](#architecture-overview-️)\n     - [Mandatory Services](#1-mandatory-services)\n     - [Bonus Services](#2-bonus-services)\n     - [Additional Services](#3-additional-services)\n   - [Key Technical Requirements](#key-technical-requirements-)\n     - [Base Image Choice](#1-base-image-choice)\n     - [Container Organization](#2-container-organization)\n     - [Data Management](#3-data-management)\n     - [Networking](#4-networking)\n     - [Configuration](#5-configuration)\n   - [Project Structure](#project-structure-)\n\n3. [Docker Fundamentals](#docker-fundamentals-)\n   - [What is Docker?](#what-is-docker)\n   - [Why Docker?](#why-docker-)\n   - [Key Docker Components](#key-docker-components-)\n   - [Docker in Inception Project](#docker-in-inception-project-)\n     - [Traditional Docker vs. Inception Approach](#traditional-docker-vs-inception-approach)\n     - [Why Build From Scratch?](#why-build-from-scratch)\n     - [Project Implementation](#project-implementation)\n   - [Process Management](#docker-process-management-and-pid-1-)\n     - [Understanding PID 1](#understanding-pid-1-in-docker-)\n     - [Why PID 1 Matters](#why-pid-1-matters-)\n     - [Implementation Best Practices](#our-implementation-best-practices-)\n     - [Testing Implementation](#testing-our-implementation-)\n   - [ENTRYPOINT vs CMD](#entrypoint-vs-cmd-deep-dive-)\n     - [Understanding Differences](#understanding-the-differences)\n     - [Common Patterns](#common-patterns)\n     - [Project Examples](#inception-project-examples)\n     - [Best Practices](#best-practices-summary-)\n\n4. [All Alpine](#all-alpine-️)\n   - [The Alpine Choice](#the-alpine-choice)\n   - [Why Alpine?](#why-alpine)\n     - [Size Matters](#size-matters-)\n     - [Security First](#security-first-️)\n     - [Package Management](#package-management-)\n   - [Implementation in Inception](#implementation-in-inception)\n   - [Impact on Services](#impact-on-services)\n   - [Trade-offs and Considerations](#trade-offs-and-considerations)\n\n5. [Core Services](#core-services)\n   - [NGINX](#core-services-nginx-)\n     - [What is NGINX?](#what-is-nginx-)\n     - [Why NGINX?](#why-nginx-)\n     - [Security Benefits](#security-benefits-️)\n     - [Performance Advantages](#performance-advantages-)\n     - [Service Integration Benefits](#service-integration-benefits-)\n     - [Technical Implementation](#technical-implementation-)\n   - [WordPress](#core-services-wordpress-)\n     - [What is WordPress?](#what-is-wordpress-)\n     - [Why WordPress + PHP-FPM?](#why-wordpress--php-fpm-)\n     - [Architecture Benefits](#architecture-benefits-️)\n     - [Technical Implementation](#technical-implementation--1)\n     - [WordPress Initialization](#wordpress-initialization-)\n     - [Security Implementation](#security-implementation-)\n     - [Performance Optimization](#performance-optimization-)\n   - [MariaDB](#core-services-mariadb-️)\n     - [What is MariaDB?](#what-is-mariadb-)\n     - [Why MariaDB?](#why-mariadb-)\n     - [Architecture Benefits](#architecture-benefits-️-1)\n     - [Technical Implementation](#technical-implementation--2)\n     - [MariaDB Configuration](#mariadb-configuration)\n     - [Database Initialization](#database-initialization)\n     - [Security Implementation](#security-implementation--1)\n     - [Performance Optimization](#performance-optimization--1)\n\n6. [Bonus Services](#bonus-services)\n   - [Adminer](#bonus-services-adminer-️)\n     - [What is Adminer?](#what-is-adminer-)\n     - [Why Adminer?](#why-adminer-)\n     - [Architecture Benefits](#architecture-benefits-️-2)\n     - [Technical Implementation](#technical-implementation--3)\n     - [Security Implementation](#security-implementation--2)\n     - [Performance Optimization](#performance-optimization--2)\n   - [Redis](#bonus-services-redis-)\n     - [What is Redis?](#what-is-redis-)\n     - [Why Redis?](#why-redis-)\n     - [Technical Implementation](#technical-implementation--4)\n     - [WordPress Integration](#wordpress-integration-1)\n     - [Security and Performance](#security-and-performance-️)\n   - [FTP/FTPS](#bonus-services-ftpftps-)\n     - [What is VSFTPD?](#what-is-vsftpd-)\n     - [Why VSFTPD?](#why-vsftpd-)\n     - [Technical Implementation](#technical-implementation--5)\n     - [VSFTPD Configuration](#vsftpd-configuration)\n     - [SSL Certificate Management](#ssl-certificate-management)\n     - [Security and Performance](#security-and-performance--1)\n   - [Gatsby App](#bonus-services-gatsby-app-)\n     - [What is Gatsby?](#what-is-gatsby-)\n     - [Why Gatsby?](#why-gatsby-)\n     - [Implementation](#implementation-)\n   - [Alien Eggs Game](#bonus-services-alien-eggs-game-)\n     - [What is Alien Eggs?](#what-is-alien-eggs-)\n     - [Implementation Features](#implementation-features-)\n     - [Technical Setup](#technical-setup-)\n     - [Monitoring Features](#monitoring-features-)\n\n7. [Additional Services](#additional-services)\n   - [cAdvisor](#monitoring-services-cadvisor-)\n     - [What is cAdvisor?](#what-is-cadvisor-)\n     - [Why cAdvisor?](#why-cadvisor-)\n     - [Implementation](#implementation--1)\n     - [Metrics Collection](#metrics-collection-)\n   - [Prometheus](#monitoring-services-prometheus-)\n     - [What is Prometheus?](#what-is-prometheus-)\n     - [Why Prometheus?](#why-prometheus-)\n     - [Implementation](#implementation--2)\n     - [Service Setup](#service-setup-️)\n     - [Monitoring Integration](#monitoring-integration-)\n   - [Grafana](#monitoring-services-grafana-)\n     - [What is Grafana?](#what-is-grafana-)\n     - [Why Grafana?](#why-grafana-)\n     - [Implementation](#implementation--3)\n     - [Security and Maintenance](#security-and-maintenance-️)\n\n8. [Conclusion](#Conclusion-)\n   - [Project Overview](#project-overview)\n   - [Key Takeaways](#key-takeaways)\n   - [Moving Forward](#moving-forward)\n\n9. [A Word from the container abyss](#a-word-from-the-abyss-)\n\n---\n\n\u003c!--=====================================\n=            PREREQUISITES              =\n======================================--\u003e\n\n# Prerequisites 🔧\n\nBefore diving into the Inception project, ensure your system meets all the necessary requirements and has the required software installed.\n\n## System Requirements\n\n- Linux-based operating system (Ubuntu 20.04 LTS recommended)\n- At least 4GB of RAM\n- At least 10GB of free disk space\n\n## Software Dependencies\n\n1. **Docker Engine**\n   ```bash\n   # For Ubuntu\n   sudo apt-get update\n   sudo apt-get install docker.io\n   ```\n\n2. **Docker Compose**\n   ```bash\n   sudo apt-get install docker-compose\n   ```\n\n3. **Make**\n   ```bash\n   sudo apt-get install make\n   ```\n\n## Environment Setup\n\n1. **Configure Hosts File**\n   \n   Add your domain to `/etc/hosts`. The domain should match the `DOMAIN_NAME` variable in your `/srcs/.env` file:\n   ```bash\n   sudo echo \"127.0.0.1 ${DOMAIN_NAME}\" \u003e\u003e /etc/hosts\n   ```\n\n   *⚠️ Note: The `.env` file should be located in the `/srcs` directory, at the same level as the `docker-compose.yml` file.*\n\n2. **Verify Docker Service**\n   ```bash\n   sudo systemctl start docker\n   sudo systemctl enable docker\n   ```\n\n3. **Add User to Docker Group** (optional, to run Docker without sudo)\n   ```bash\n   sudo usermod -aG docker ${USER}\n   newgrp docker\n   ```\n\n## Installation Steps\n\n1. **Clone the Repository**\n   ```bash\n   git clone https://github.com/Nihilantropy/Inception.git\n   ```\n\n2. **Navigate to Project Directory**\n   ```bash\n   cd Inception\n   ```\n\n3. **Start the Infrastructure**\n   ```bash\n   make\n   ```\n\nAfter running `make`, the script will:\n- Set up necessary directories\n- Build Docker images\n- Start all containers\n- Configure the services\n\nYou can verify the installation by accessing the WordPress site at `https://${DOMAIN_NAME}`.\n\n*⚠️ Note: You could use docker-desktop, this is only a recommended setup. Initial configuration might be different*\n\n---\n\n\u003c!--=====================================\n=         PROJECT OVERVIEW            =\n======================================--\u003e\n## What is Inception?\n\nInception is an advanced system administration project that challenges you to build and orchestrate a complete infrastructure using Docker containerization. The project simulates a real-world production environment where multiple services work together to deliver a robust web application stack.\n\n\u003c!--=====================================\n=         PROJECT GOALS               =\n======================================--\u003e\n## Project Goals 🎯\n\nThe main objectives of Inception are:\n\n1. **Containerization Mastery**: Learn to build and manage Docker containers from scratch, without using pre-built images\n2. **Service Orchestration**: Create a multi-service infrastructure where each component runs in its own container\n3. **Infrastructure as Code**: Implement all configurations through scripts, ensuring reproducibility and maintainability\n4. **Security Implementation**: Set up secure communication between services and implement proper access controls\n\n\u003c!--=====================================\n=       ARCHITECTURE OVERVIEW         =\n======================================--\u003e\n## Architecture Overview 🏗️\n\nThe Inception infrastructure consists of:\n\n### 1. Mandatory Services\n- 🌐 **NGINX**: Acts as a reverse proxy with SSL/TLS termination  \n- 🖥️ **WordPress + PHP-FPM**: Main application server  \n- 🗄️ **MariaDB**: Database server for persistent data storage  \n\n### 2. Bonus Services\n- ⚡ **Redis**: Caching system for WordPress optimization  \n- 📂 **VSFTPD**: FTP server for file management  \n- 📊 **Adminer**: Database management interface  \n- 🚀 **Gatsby**: Static site generator for additional content  \n- 🎮 **Custom Game Integration**: Demonstrating versatile deployment capabilities  \n\n### 3. Additional Services\n- 📈 **Prometheus**: Metrics collection and storage  \n- 📉 **Grafana**: Visualization and dashboard creation  \n- 🛠️ **cAdvisor**: Container metrics collection\n\n![Inception Architecture](images/inception-architecture.png)\n\n*Note: The monitoring services are neither part of the mandatory requirements nor the bonus part. They were added as a learning exercise to explore container monitoring.*\n\n\u003c!--=====================================\n=     TECHNICAL REQUIREMENTS          =\n======================================--\u003e\n## Key Technical Requirements 📋\n\n1. **Base Image Choice**\n   - Containers must use either Alpine Linux or Debian as their base image\n   - In this implementation, we chose Alpine Linux (rationale detailed in later sections)\n   - Custom Dockerfiles must be written for each service\n   - No use of pre-built Docker images from Docker Hub\n\n2. **Container Organization**\n   - Each service runs in its dedicated container\n   - Services must automatically restart on failure\n   - Proper resource isolation between containers\n\n3. **Data Management**\n   - Persistent data storage through Docker volumes\n   - Efficient backup and restore capabilities\n   - Data integrity across container restarts\n\n4. **Networking**\n   - Isolated Docker networks for different service groups\n   - Secure internal communication\n   - External access only through designated ports\n\n5. **Configuration**\n   - All setup performed through initialization scripts\n   - Environment variable management\n   - No manual intervention in container configuration\n\n\u003c!--=====================================\n=         PROJECT STRUCTURE           =\n======================================--\u003e\n## Project Structure 📁\n\nThe project follows a clear organizational structure:\n\n```\ninception/\n├── srcs/\n│   ├── docker-compose.yml\n│   └── requirements/\n│       ├── nginx/\n│       ├── wordpress/\n│       ├── mariadb/\n│       └── bonus/\n│           ├── redis/\n│           ├── ftp/\n│           ├── adminer/\n│           ├── gatsby-app/\n│           └── monitoring/  # Additional services\n└── Makefile\n```\n\nThis structure ensures:\n- Clear separation of services\n- Easy maintenance and updates\n- Scalable architecture\n- Efficient development workflow\n\nThe Inception project represents a comprehensive approach to modern infrastructure deployment, combining security, efficiency, and maintainability in a containerized environment. 🌟\n\n---\n\n\u003c!--=====================================\n=         DOCKER FUNDAMENTALS         =\n======================================--\u003e\n# Docker Fundamentals 🐳\n\n## What is Docker?\n\nDocker is a platform for developing, shipping, and running applications in isolated environments called containers. A container is a lightweight, standalone package that includes everything needed to run a piece of software - from the code and runtime to system libraries and settings.\n\n![VM vs Containers](images/vm-vs-containers.png)\n\n\u003c!--=====================================\n=         DOCKER BENEFITS             =\n======================================--\u003e\n## Why Docker? 🤔\n\nDocker solves several key challenges in modern software development:\n\n1. **Consistency**: \"It works on my machine\" becomes a problem of the past\n2. **Isolation**: Applications run independently without interfering with each other\n3. **Efficiency**: Containers share the host OS kernel, making them lighter than VMs\n4. **Scalability**: Easy to deploy multiple instances of the same application\n\n## Key Docker Components 🔧\n\n- **Dockerfile**: A text file containing instructions to build an image\n- **Image**: A template for creating containers (like a snapshot)\n- **Container**: A running instance of an image\n- **Docker Compose**: Tool for defining and running multi-container applications\n\n\u003c!--=====================================\n=         DOCKER IN INCEPTION         =\n======================================--\u003e\n## Docker in Inception Project 🎯\n\n### Traditional Docker vs. Inception Approach\n\n**Traditional Approach:**\n```bash\n# Pulling pre-built images\ndocker pull wordpress:latest\ndocker pull mysql:latest\n```\n\n**Inception Approach:**\n```dockerfile\n# Building custom WordPress image\nFROM alpine:3.20\nRUN apk add --no-cache php php-fpm wordpress\n# Custom configurations...\n```\n\n### Why Build From Scratch?\n\n1. **Understanding**: Gain deep knowledge of service configuration\n2. **Control**: Full control over what goes into each container\n3. **Security**: Minimize vulnerabilities by including only necessary components\n4. **Optimization**: Create lean containers tailored to specific needs\n\n![Docker Approaches](images/docker-approaches.png)\n\n### Project Implementation\n\nIn Inception, we:\n- Write custom Dockerfiles for each service\n- Configure services through initialization scripts\n- Use docker-compose for orchestration\n- Implement proper networking and volume management\n\nThis approach provides valuable learning opportunities and better control over the infrastructure, though in production environments, validated official images might be preferred for their reliability and maintenance.\n\n\u003c!--=====================================\n=         PROCESS MANAGEMENT          =\n======================================--\u003e\n## Docker Process Management and PID 1 🔄\n\n## Understanding PID 1 in Docker 🎯\n\nIn Docker containers, the first process that starts (PID 1) plays a crucial role in process management and container lifecycle. Unlike traditional Linux systems where systemd or init handles process management, in containers, your application or a designated init process must handle these responsibilities.\n\n### Why PID 1 Matters 🤔\n\n1. **Signal Handling**\n   - PID 1 must properly handle process signals (SIGTERM, SIGINT, etc.)\n   - Responsible for forwarding signals to child processes\n   - Critical for graceful container shutdown\n\n2. **Zombie Process Prevention**\n   - Must reap zombie (defunct) processes\n   - Prevent resource leaks\n   - Maintain container health\n\n3. **Container Lifecycle**\n   - Determines container state\n   - Manages application startup\n   - Handles cleanup on shutdown\n\n## Our Implementation: Best Practices ✅\n\nIn our Inception project, we implement a robust solution for process management that ensures proper signal handling and clean container lifecycle management. Here's how:\n\n### 1. ENTRYPOINT in Exec Form\n\nWe use the exec form of ENTRYPOINT in our Dockerfiles:\n```dockerfile\nENTRYPOINT [\"/init.sh\"]\n```\n\nThis is crucial because:\n- Runs the init script directly, not through a shell\n- Makes our init script PID 1 initially\n- Ensures proper signal propagation\n- Prevents additional shell processes\n\n### 2. Init Scripts with exec\n\nOur init scripts end with the `exec` command:\n```bash\n#!/bin/sh\nset -e\n\n# Configuration and setup...\n\n# Replace shell with the main process\nexec nginx -g \"daemon off;\"\n```\n\nThis approach is ideal because:\n- The `exec` command replaces the shell process with the service process\n- The service becomes PID 1 directly\n- No shell remains in between Docker and the service\n- Professional services (NGINX, PHP-FPM, MariaDB) handle signals properly\n\n### Why Our Approach Works Well 🎯\n\n1. **No Shell Interference**\n   - Using exec form of ENTRYPOINT avoids shell wrapping\n   - `exec` in scripts ensures direct process execution\n   - No intermediate shell processes remain\n\n2. **Professional Service Integration**\n   - Services like NGINX, MariaDB, and PHP-FPM have built-in signal handling\n   - They manage their own child processes\n   - They handle graceful shutdowns properly\n\n3. **Clean Process Tree**\n   ```\n   PID 1 (Service Process)\n   └── Child processes (if any)\n   ```\n   No unnecessary layers or shell processes\n\n4. **Direct Signal Propagation**\n   ```\n   Docker -\u003e Service Process (PID 1)\n              └── Clean shutdown handling\n   ```\n   No signal forwarding needed\n\n### Examples from Our Services\n\n1. **NGINX**\n```bash\nexec nginx -g \"daemon off;\"\n```\nNGINX receives signals directly and handles graceful shutdown of worker processes.\n\n2. **PHP-FPM**\n```bash\nexec php-fpm82 -F\n```\nPHP-FPM manages its worker pool and handles signals for graceful worker shutdown.\n\n3. **MariaDB**\n```bash\nexec mysqld --datadir=\"$MARIADB_DATA_DIR\" --user=mysql\n```\nMariaDB handles database connections and ensures proper cleanup on shutdown.\n\n### Why We Don't Need Additional Signal Handling\n\nDespite what some examples show, we don't need explicit signal handling in our init scripts because:\n\n1. We use the exec form of ENTRYPOINT: `ENTRYPOINT [\"/init.sh\"]`\n2. Our init scripts use `exec` to replace themselves with the service\n\nThe key is that there's never a shell sitting between Docker and our service processes. When Docker sends a signal, it goes directly to the service process, which knows how to handle it properly.\n\n## Testing Our Implementation ✅\n\nYou can verify our implementation works correctly by:\n\n```bash\n# Graceful shutdown test\ndocker-compose stop\n\n# Check logs for clean shutdown\ndocker-compose logs nginx\n\n# Verify no zombie processes\ndocker top nginx\n```\n\nThis setup provides clean process management and proper signal handling while maintaining simplicity and reliability. 🚀\n\n## ENTRYPOINT vs CMD Deep Dive 🔍\n\n### Understanding the Differences\n\n1. **ENTRYPOINT**\n   - Defines the executable to run\n   - Hard to override (requires --entrypoint flag)\n   - Receives CMD as arguments\n   - Better for \"executable\" containers\n\n2. **CMD**\n   - Provides default arguments\n   - Easily overridden at runtime\n   - Can be completely replaced\n   - Flexible for general use\n\n### Common Patterns\n\n1. **Executable with Default Arguments**\n```dockerfile\nENTRYPOINT [\"nginx\"]\nCMD [\"-g\", \"daemon off;\"]\n```\n- ENTRYPOINT defines the executable\n- CMD provides default arguments\n- Can override arguments but not executable\n\n2. **Single Command with Init**\n```dockerfile\nENTRYPOINT [\"/init.sh\"]\n```\n- Script handles all setup and execution\n- No default arguments needed\n- Clear entry point for container\n\n3. **Flexible Command**\n```dockerfile\nCMD [\"php-fpm\"]\n```\n- Can be completely overridden\n- Suitable for development containers\n- Maximum flexibility\n\n### Inception Project Examples\n\n1. **NGINX Container**\n```dockerfile\nCOPY --chown=nginx:nginx ./tools/init.sh /init.sh\nRUN chmod +x /init.sh\nENTRYPOINT [\"/init.sh\"]\n```\n- Uses init script for setup\n- Handles SSL configuration\n- Manages process lifecycle\n\n2. **Alien-Eggs Container**\n```dockerfile\nENTRYPOINT [ \"python3\", \"/app/src/serve.py\" ]\nCMD [\"--root\", \"/app/src\", \"--no-browser\", \"--port\", \"8060\", \"--metrics-port\", \"8000\"]\n```\n- Direct process execution\n- Configuration via arguments\n- No complex initialization needed\n\n## Best Practices Summary 📋\n\n1. **Process Management**\n   - Use init scripts for complex services\n   - Implement proper signal handling\n   - Manage child processes effectively\n   - Handle cleanup on shutdown\n\n2. **ENTRYPOINT Usage**\n   - Use for primary executable\n   - Initialize environment if needed\n   - Handle signals properly\n   - Set up logging\n\n3. **CMD Considerations**\n   - Provide default arguments\n   - Allow runtime flexibility\n   - Consider development needs\n   - Enable easy overrides\n\n4. **General Guidelines**\n   - One main process per container\n   - Proper signal handling\n   - Clear process ownership\n   - Efficient cleanup procedures\n\nFollowing these practices ensures robust container operation, proper process management, and reliable service execution in our infrastructure. 🚀\n\n---\n\n\u003c!--=====================================\n=         ALPINE LINUX                =\n======================================--\u003e\n# All Alpine 🏔️\n\n## The Alpine Choice\n\nIn Inception, we had the choice between Debian and Alpine Linux as base images for our containers. We chose Alpine Linux for all our services, a decision that brings specific advantages to our containerized infrastructure.\n\n\u003c!--=====================================\n=         ALPINE BENEFITS             =\n======================================--\u003e\n## Why Alpine? \n\n### Size Matters 📦\n- **Minimal Base Image**: Alpine base image is ~5MB compared to Debian's ~114MB\n- **Smaller Final Images**: Services built on Alpine typically result in 30-70% smaller images\n- **Faster Deployments**: Smaller images mean quicker pulls and deployments\n\n### Security First 🛡️\n- **Minimal Attack Surface**: Fewer installed packages means fewer potential vulnerabilities\n- **Security-oriented**: Built with security in mind from the ground up\n- **Regular Security Updates**: Active maintenance and quick security patches\n\n### Package Management 🔧\n- **Simple Package Manager**: `apk` is fast, simple, and efficient\n- **Rich Package Repository**: Despite its size, Alpine provides most needed packages\n- **Quick Updates**: Package installation and updates are notably faster than apt\n\n![Alpine vs Debian Sizes](images/debian-vs-alpine.png)\n\n\u003c!--=====================================\n=         ALPINE IMPLEMENTATION       =\n======================================--\u003e\n## Implementation in Inception\n\n### Base Image Declaration\n```dockerfile\n# All our Dockerfiles start with\nFROM alpine:3.20\n```\n\n### Package Installation Pattern\n```dockerfile\n# Alpine's efficient package installation\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    package1 \\\n    package2 \\\n    package3\n```\n\n### Key Considerations\n\n1. **Compatibility**\n   - Most services work seamlessly on Alpine\n   - Some packages might have slightly different names than in Debian\n   - Occasional need to install additional dependencies\n\n2. **Learning Curve**\n   - Different package names from Debian/Ubuntu\n   - Simpler init system\n   - Streamlined configuration approaches\n\n3. **Advantages in Our Setup**\n   - Reduced resource usage across all containers\n   - Faster container startup times\n   - Simplified dependency management\n\n\u003c!--=====================================\n=         SERVICE BENEFITS            =\n======================================--\u003e\n## Impact on Services\n\nEach service benefits from Alpine in specific ways:\n\n- **NGINX**: Lightweight reverse proxy with minimal overhead\n- **WordPress**: Efficient PHP-FPM implementation\n- **MariaDB**: Optimized database server with smaller footprint\n- **Redis**: Fast caching with minimal resource usage\n- **Monitoring Stack**: Efficient metrics collection and storage\n\n\u003c!--=====================================\n=         CONSIDERATIONS              =\n======================================--\u003e\n## Trade-offs and Considerations\n\nWhile Alpine is excellent for our use case, it's important to note:\n\n1. **Production Consideration**\n   - Some teams prefer Debian for its familiarity\n   - Larger community support for Debian-based solutions\n   - More extensive documentation available\n\n2. **Development Workflow**\n   - Need to adapt to Alpine-specific commands\n   - Different debugging tools and processes\n   - Slightly different configuration paths\n\nThe choice of Alpine aligns perfectly with Inception's goals of understanding container infrastructure while maintaining efficient resource usage and security. 🎯\n\n---\n\n# Core Services: NGINX 🚀\n\n![NGINX ART](images/nginx-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is NGINX? 🌐\n\nNGINX (pronounced \"engine-x\") is a powerful, open-source software that functions as a web server, reverse proxy, load balancer, and HTTP cache. Originally designed to solve the C10K problem (handling 10,000 concurrent connections), NGINX has become one of the most popular web servers worldwide due to its efficiency and low resource consumption.\n\n![NGINX Gateway](images/nginx-gateway.png)\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why NGINX? 🤔\n\nIn our Inception project, NGINX serves as the primary gateway to all our services:\n\n1. **Single Entry Point** 🚪\n   - All external traffic flows through NGINX\n   - Centralized access control and monitoring\n   - Simplified security management\n\n2. **SSL/TLS Termination** 🔐\n   - Handles all HTTPS encryption/decryption\n   - Centralizes certificate management\n   - Internal services communicate over unencrypted channels\n\n3. **Reverse Proxy** 🔄\n   - Routes requests to appropriate backend services\n   - Hides internal infrastructure details\n   - Provides URL path-based routing\n\n## Security Benefits 🛡️\n\n1. **TLS Communication**\n   - Forces HTTPS for all connections\n   - Implements modern TLS protocols (1.2 and 1.3)\n   - Strong cipher suite configuration\n\n2. **Network Isolation**\n   - Backend services aren't directly exposed\n   - Internal network segmentation\n   - Minimized attack surface\n\n## Performance Advantages ⚡\n\n1. **Efficient Static File Serving**\n   - Optimized for serving static content\n   - Reduces load on application servers\n   - Implements caching strategies\n\n2. **Connection Handling**\n   - Event-driven architecture\n   - Excellent concurrent connection handling\n   - Low memory footprint\n\n## Service Integration Benefits 🔌\n\n1. **WordPress Integration**\n   - Serves static files directly\n   - Routes PHP requests to PHP-FPM\n   - Manages cache headers\n\n2. **Monitoring Stack**\n   - Routes to Prometheus/Grafana\n   - URL path-based access\n   - Consistent authentication\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Technical Implementation 🔧\n\n### 1. Docker Compose Configuration\n\n```yaml\nnginx:\n    container_name: nginx\n    image: nginx\n    build:\n      context: ./requirements/nginx\n      dockerfile: Dockerfile\n    env_file:\n      - .env\n    ports:\n      - \"443:443\"\n    networks:\n      - proxy\n    depends_on:\n      - mariadb\n      - wordpress\n      - ftp\n      - redis\n      - adminer\n      - gatsby-app\n      - alien-eggs\n      - prometheus\n      - grafana\n      - cadvisor\n    volumes:\n      - wp-data:/var/www/html\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD\", \"nginx\", \"-t\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 30s\n```\n\n#### Key Elements Analysis:\n\n1. **Volume Mount (`/var/www/html`)**:\n   - Essential for serving WordPress files\n   - The `wp-data` volume is shared between WordPress and NGINX\n   - NGINX needs direct access to these files to serve static content efficiently\n   - Without this mount, NGINX couldn't serve WordPress media or static assets\n\n2. **Port 443**:\n   - Only HTTPS port is exposed\n   - No HTTP (port 80) access enforces secure connections\n   - Internal service communication doesn't need port exposure\n   - Maps container's internal port 443 to host's port 443\n\n3. **Network Configuration**:\n   - Connected only to `proxy` network\n   - Isolates NGINX from database network\n   - Enables communication with backend services\n   - Follows principle of least privilege\n\n\u003c!--=====================================\n=         DOCKERFILE SETUP            =\n======================================--\u003e\n\n### 2. Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\nRUN apk add --no-cache \\\n    nginx \\\n    openssl \\\n    apache2-utils \\\n    curl \\\n    shadow\n\nRUN mkdir -p /var/www/html \u0026\u0026 \\\n    chown -R nginx:www-data /var/www/html\n\nRUN usermod -aG www-data nginx\n\nCOPY --chown=nginx:nginx ./tools/init.sh /init.sh\nRUN chmod +x /init.sh\n\nENTRYPOINT [\"/init.sh\"]\n```\n\n#### Package Analysis:\n\n1. **Core Packages**:\n   - `nginx`: Main web server package\n   - `openssl`: Required for SSL certificate generation and management\n   - `apache2-utils`: Provides useful tools like `htpasswd`\n   - `curl`: Used for network testing and health checks\n   - `shadow`: Required for user/group management\n\n2. **Directory Setup**:\n   - Creates `/var/www/html` directory\n   - Sets ownership to nginx:www-data\n   - Ensures proper permissions for file access\n\n3. **User Configuration**:\n   - Adds NGINX user to www-data group\n   - Enables proper file access permissions\n   - Follows security best practices\n\n\u003c!--=====================================\n=       INITIALIZATION SCRIPT         =\n======================================--\u003e\n\n### 3. Initialization Script Analysis 📝\n\n1. **Initial Setup** (`set -e`):\n   - Ensures script stops on any error\n   - Critical for preventing partial configurations\n   - Makes troubleshooting easier\n\n2. **Directory Structure**:\n   - `/etc/nginx/certs`: SSL certificate storage\n   - `/var/log/nginx`: Log file location\n   - `/var/www/html`: Web root directory\n   - `/run/nginx`: Runtime files location\n\n3. **SSL Certificate Generation**:\n   - Checks for existing certificates\n   - Generates self-signed certificate if needed\n   - Uses environment variables for paths\n   - Sets certificate details via `-subj` parameter\n\n4. **Configuration File Generation**:\n   - Creates main NGINX configuration\n   - Uses heredoc for clean configuration writing\n   - Environment variable substitution\n   - Sets up all necessary server blocks\n\n5. **Configuration Elements**:\n   - SSL configuration\n   - Server block setup\n   - Proxy configurations\n   - Location blocks for different services\n\n6. **Error Handling**:\n   - Built-in error checking\n   - Clear error messages\n   - Proper exit codes\n   - Configuration validation\n\n### Take a look :mag:!\n```bash\ncat /srcs/requirements/nginx/tools/init.sh\n```\n\n---\n\n# Core Services: WordPress 🎨\n\n![WORDPRESS ART](images/wordpress-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is WordPress? 📝\n\nWordPress is the world's most popular content management system (CMS), powering over 20% of all websites. In our Inception infrastructure, WordPress runs with PHP-FPM (FastCGI Process Manager) for optimal performance and resource utilization. This setup separates the PHP processing from the web server, allowing for better scaling and resource management.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why WordPress + PHP-FPM? 🤔\n\nOur WordPress implementation focuses on three key aspects:\n\n1. **Performance Optimization** ⚡\n   - PHP-FPM process management\n   - Redis cache integration\n   - Optimized PHP configuration\n\n2. **Security Hardening** 🛡️\n   - Custom user configuration\n   - File permission management\n   - Secure WordPress settings\n\n3. **Integration** 🔌\n   - MariaDB database connection\n   - Redis cache coordination\n   - NGINX communication\n   - FTP service coordination\n\n## Architecture Benefits 🏗️\n\n1. **FastCGI Processing**\n   - Separate PHP process management\n   - Dynamic process scaling\n   - Efficient resource utilization\n\n2. **File System Organization**\n   - Structured content storage\n   - Shared volume management\n   - Proper permissions hierarchy\n\n3. **Cache Integration**\n   - Redis object caching\n   - Session handling\n   - Persistent cache storage\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Technical Implementation 🔧\n\n### 1. Docker Compose Configuration\n\n```yaml\nwordpress:\n    container_name: wordpress\n    image: wordpress\n    env_file:\n      - .env\n    build:\n      context: ./requirements/wordpress\n      dockerfile: Dockerfile\n    volumes:\n      - wp-data:/var/www/html\n    networks:\n      - backend-db\n      - proxy\n      - cache\n    depends_on:\n      - mariadb\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD\", \"php-fpm82\", \"-t\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 30s\n```\n\n#### Key Elements Analysis:\n\n1. **Volume Configuration**:\n   - `wp-data` volume stores WordPress files\n   - Shared with `NGINX`, `FTP` and `REDIS` for file access\n   - Persists through container restarts\n   - Maintains proper file permissions\n\n2. **Network Setup**:\n   - Connected to `backend-db`, `proxy` and `cache` networks\n   - Enables database and cache access\n   - Allows NGINX communication\n   - Maintains network isolation\n\n3. **Dependencies**:\n   - Requires MariaDB for database\n   - Ensures proper startup order\n   - Maintains service availability\n\n\u003c!--=====================================\n=         DOCKERFILE SETUP            =\n======================================--\u003e\n\n### 2. Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    php82 \\\n    php82-fpm \\\n    php82-mysqli \\\n    php82-curl \\\n    php82-json \\\n    php82-zip \\\n    php82-gd \\\n    php82-mbstring \\\n    php82-xml \\\n    php82-session \\\n    php82-opcache \\\n    php82-phar \\\n    php82-pecl-redis \\\n    php82-ctype \\\n    php82-ftp \\ \n    mariadb-client \\\n    curl \\\n    bash \\\n    \u0026\u0026 ln -s /usr/bin/php82 /usr/bin/php\n\nRUN adduser -S -G www-data www-data\n\nCOPY ./tools/init-wp-config.sh /usr/local/bin/init-wp-config.sh\nCOPY ./tools/init-wordpress.sh /usr/local/bin/init-wordpress.sh\nCOPY ./tools/setup_db.sh /usr/local/bin/setup_db.sh\n\nRUN chmod +x /usr/local/bin/init-wp-config.sh \u0026\u0026 \\\n    chmod +x /usr/local/bin/init-wordpress.sh \u0026\u0026 \\\n    chmod +x /usr/local/bin/setup_db.sh \u0026\u0026 \\\n    mkdir -p /var/www/html \u0026\u0026 \\\n    chown -R www-data:www-data /var/www/html \u0026\u0026 \\\n    chmod -R 755 /var/www/html\n\nEXPOSE 9000\n\nENTRYPOINT [\"/usr/local/bin/init-wp-config.sh\"]\n```\n\n#### Package Analysis:\n\n1. **PHP Core \u0026 Extensions**:\n   - `php82-fpm`: FastCGI Process Manager\n   - `php82-mysqli`: MySQL database support\n   - `php82-pecl-redis`: Redis integration\n   - `php82-ftp`: FTP integration\n   - Various required PHP extensions\n\n2. **Additional Tools**:\n   - `mariadb-client`: Database management\n   - `curl`: Network operations\n   - `bash`: Script execution\n\n3. **User \u0026 Permission Management**:\n   - Creates www-data user and group\n   - Critical for secure file operations\n   - Enables proper service coordination\n\n   The www-data user is crucial in our setup:\n   - **Security**: Provides a non-root user for running PHP-FPM processes\n   - **File Access**: Coordinates file permissions between NGINX, WordPress, and FTP\n   - **Process Isolation**: Ensures PHP processes run with minimal privileges\n   - **Service Coordination**: Enables seamless operation between NGINX, PHP-FPM, WordPress, and FTP\n   - **Shared Ownership**: Manages shared volume access across containers\n   - **FTP Integration**: Ensures FTP users can properly interact with WordPress files\n   \n   The www-data group is particularly important for FTP operations:\n   - FTP users are added to the www-data group\n   - Enables proper file modifications through FTP\n   - Maintains correct permissions for WordPress operations\n   - Allows secure file uploads via FTP\n   - Prevents permission conflicts between services\n\n\u003c!--=====================================\n=     INITIALIZATION PROCESS          =\n======================================--\u003e\n\n### 3. WordPress Initialization 🔄\n\nThe initialization process follows a structured approach:\n\n1. **Configuration Setup** (`init-wp-config.sh`):\n   - WordPress configuration file creation\n   - Database connection setup\n   - Redis cache configuration\n   - FTP server configuration\n   - Security keys generation\n\n2. **WordPress Core** (`init-wordpress.sh`):\n   - Core files installation\n   - Initial site setup\n   - User creation\n   - Plugin activation\n\n3. **Database Integration** (`setup_db.sh`):\n   - Database connection verification\n   - Table creation/verification\n   - Initial data population\n   - User permissions setup\n\n### 4. Key Configuration Elements 🎛️\n\n1. **custom wp-config**\ninit-wp-config.sh script create a custom `wp-config.php` file,\ntailored around our needs.\nUsing the `cat` command ensure proper ENV `var expansion`.\n\n2. **PHP-FPM Settings**:\n`Point 9` of the `init-wordpress.sh` script ensure proper `php-fpm` setup\nby changing the default `user`, `group` and `listen` interface to our needs\n\n```bash\nsed -i -r 's|^user = .*$|user = www-data|' /etc/php82/php-fpm.d/www.conf\nsed -i -r 's|^group = .*$|group = www-data|' /etc/php82/php-fpm.d/www.conf\nsed -i -r 's|listen = 127.0.0.1:9000|listen = 0.0.0.0:9000|' /etc/php82/php-fpm.d/www.conf\n```\n\n\u003c!--=====================================\n=         SECURITY MEASURES           =\n======================================--\u003e\n\n## Security Implementation 🔒\n\n1. **File Permissions and www-data Role**:\n   - WordPress files: 644 (owned by www-data:www-data)\n   - Directories: 755 (owned by www-data:www-data)\n   - Sensitive files: 600 (owned by www-data:www-data)\n   - wp-content: 775 (owned by www-data:www-data)\n\n   The www-data ownership is essential because:\n   - NGINX worker processes run as www-data\n   - PHP-FPM processes run as www-data\n   - WordPress needs to write to wp-content\n   - Ensures proper file access between services\n   - Prevents permission-related errors during plugin/theme installations\n\n2. **Database Security**:\n   - Separate user accounts\n   - Limited privileges\n   - Prepared statements\n   - Secure connections\n\n3. **WordPress Hardening**:\n   - Custom table prefix\n   - Disabled file editing\n   - Secure authentication keys\n   - Limited login attempts\n\n\u003c!--=====================================\n=         CORE CONFIGURATION            =\n======================================--\u003e\n\n## Core configuration ⚡\n\n1. **Database Setup \u0026 Optimization**:\n   - Database initialization in setup_db.sh:\n     - Properly structured users table creation\n     - Default user setup\n     - Connection verification\n   - MariaDB connection configuration in wp-config.php:\n     ```php\n     define('DB_NAME', '${MYSQL_DATABASE}');\n     define('DB_USER', '${MYSQL_USER}');\n     define('DB_PASSWORD', '${MYSQL_PASSWORD}');\n     define('DB_HOST', '${MYSQL_HOST}');\n     define('DB_CHARSET', 'utf8');\n     define('DB_COLLATE', '');\n     ```\n   - Connection retry mechanism in scripts\n\n2. **Redis Integration**:\n   - Redis plugin installation and configuration in init-wordpress.sh:\n     ```bash\n     wp plugin install redis-cache --activate\n     cp wp-content/plugins/redis-cache/includes/object-cache.php wp-content/object-cache.php\n     wp redis enable\n     ```\n   - Redis configuration in wp-config.php:\n     ```php\n     define('WP_REDIS_HOST', '${REDIS_HOST}');\n     define('WP_REDIS_PORT', ${REDIS_PORT});\n     define('WP_CACHE', true);\n     define('WP_REDIS_DISABLE_METRICS', false);\n     define('WP_REDIS_METRICS_MAX_TIME', 60);\n     define('WP_REDIS_SELECTIVE_FLUSH', true);\n     define('WP_REDIS_MAXTTL', 86400);\n     ```\n\n3. **FTP integration**\n   - Thanks to the FTP configuration in the wp-config.php we can connect to the FTP (SSL) server to download and install plugins in our wordpress site\n   - Redis configuration in wp-config.php:\n     ```php\n     define('FTP_USER', '${FTP_USER}');\n     define('FTP_PASS', '${FTP_PASS}');\n     define('FTP_HOST', 'ftp:21');\n     define('FS_METHOD', 'direct');\n     define('FTP_BASE', '/var/www/html/');\n     define('FTP_CONTENT_DIR', '/var/www/html/wp-content/');\n     define('FTP_PLUGIN_DIR', '/var/www/html/wp-content/plugins/');\n     define('FTP_SSL', true);\n     define('FTP_VERIFY_SSL', false);\n     ```\n\n### Take a look :mag:!\n```bash\ncat /srcs/requirements/wordpress/tools/init-wordpress.sh\n```\n```bash\ncat /srcs/requirements/wordpress/tools/init-wp-config.sh\n```\n```bash\ncat /srcs/requirements/wordpress/tools/setup_db.sh\n```\n\nThis WordPress setup provides a robust, secure, and performant foundation for our web application, integrated seamlessly with other services in our infrastructure. 🚀\n\n---\n\n# Core Services: MariaDB 🗄️\n\n![MARIADB ART](images/mariadb-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is MariaDB? 📊\n\nMariaDB is a community-developed, commercially supported fork of MySQL that provides a robust, scalable, and reliable SQL server. In our Inception infrastructure, MariaDB serves as the primary database system, handling data persistence for WordPress and providing secure, efficient data storage and retrieval capabilities.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why MariaDB? 🤔\n\nOur MariaDB implementation focuses on three key aspects:\n\n1. **Data Persistence** 💾\n   - Reliable storage for WordPress data\n   - Transaction management\n   - Data integrity maintenance\n\n2. **Performance Optimization** ⚡\n   - Efficient query processing\n   - Memory management\n   - Connection pooling\n\n3. **Security Hardening** 🛡️\n   - User authentication\n   - Access control\n   - Network isolation\n\n## Architecture Benefits 🏗️\n\n1. **Database Management**\n   - Structured data organization\n   - ACID compliance\n   - Backup capabilities\n\n2. **Resource Efficiency**\n   - Optimized memory usage\n   - Connection pooling\n   - Query caching\n\n3. **Security Features**\n   - Authentication mechanisms\n   - Network-level security\n   - Data encryption support\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Technical Implementation 🔧\n\n### 1. Docker Compose Configuration\n\n```yaml\nmariadb:\n    container_name: mariadb\n    image: mariadb\n    build:\n      context: ./requirements/mariadb\n    env_file:\n      - .env\n    volumes:\n      - db-data:/var/lib/mysql\n    networks:\n      - backend-db\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD\", \"mysqladmin\", \"ping\", \"-h\", \"localhost\", \"-u\", \"root\", \"-p${MYSQL_ROOT_PASSWORD}\"]\n      interval: 10s\n      timeout: 5s\n      retries: 5\n      start_period: 30s\n```\n\n#### Key Elements Analysis:\n\n1. **Volume Configuration**:\n   - `db-data` volume persists database files\n   - Mounted at `/var/lib/mysql`\n   - Survives container restarts\n   - Ensures data durability\n\n2. **Network Setup**:\n   - Connected only to `backend-db` network\n   - Isolated from public access\n   - Direct access only from `WordPress` and `Adminer`\n   - Enhanced security through network segregation\n\n3. **Health Monitoring**:\n   - Regular ping checks\n   - Fast failure detection\n   - Automatic recovery\n   - Proper startup delay\n\n\u003c!--=====================================\n=         DOCKERFILE SETUP            =\n======================================--\u003e\n\n### 2. Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\nENV MARIADB_DATA_DIR=/var/lib/mysql\n\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    mariadb mariadb-client \u0026\u0026 \\\n    mkdir -p \"$MARIADB_DATA_DIR\" \u0026\u0026 \\\n    chown -R mysql:mysql \"$MARIADB_DATA_DIR\" \u0026\u0026 \\\n    mysql_install_db --user=mysql --datadir=\"$MARIADB_DATA_DIR\"\n\nRUN mkdir -p /run/mysqld \u0026\u0026 chown -R mysql:mysql /run/mysqld\n\nCOPY ./conf/my.cnf /etc/my.cnf\nCOPY ./tools/init.sh /init.sh\nRUN chmod +x /init.sh\n\nEXPOSE 3306\n\nCMD [\"/init.sh\"]\n```\n\n#### Package Analysis:\n\n1. **Core Components**:\n   - `mariadb`: Main database server\n   - `mariadb-client`: Command-line tools\n   - Essential system utilities\n\n2. **Directory Setup**:\n   - Creates data directory\n   - Sets proper ownership\n   - Initializes database files\n\n3. **Configuration**:\n   - Custom my.cnf file\n   - Initialization script\n   - Runtime directory setup\n\n\u003c!--=====================================\n=       CONFIGURATION ANALYSIS        =\n======================================--\u003e\n\n### 3. MariaDB Configuration\n\nThe `my.cnf` file contains essential MariaDB settings:\n\n```ini\n[mysqld]\nbind-address = 0.0.0.0\nport = 3306\ndatadir = /var/lib/mysql\nsocket = /run/mysqld/mysqld.sock\n\n# Recommended settings for WordPress\ncharacter-set-server = utf8mb4\ncollation-server = utf8mb4_general_ci\n\n# Performance tuning\nmax_connections = 150\ninnodb_buffer_pool_size = 128M\n\n[client]\ndefault-character-set = utf8mb4\nsocket = /run/mysqld/mysqld.sock\n```\n\n#### Configuration Elements:\n\n1. **Network Settings**:\n   - Listens on all interfaces\n   - Standard port 3306\n   - Socket configuration\n\n2. **Character Encoding**:\n   - UTF8MB4 for full Unicode support\n   - WordPress-optimized collation\n   - Consistent encoding across connections\n\n3. **Performance Settings**:\n   - Connection limit\n   - Buffer pool size\n   - Memory optimization\n\n\u003c!--=====================================\n=     INITIALIZATION PROCESS          =\n======================================--\u003e\n\n### 4. Database Initialization\n\nThe initialization script (`init.sh`) handles database setup:\n\n```bash\n#!/bin/sh\n\necho \"Creating initdb.d directory...\"\nmkdir -p initdb.d\necho \"✅ Directory created succesfully!\"\n\n# Generate initialization SQL file\necho \"Creating init.sql file for db and user setup...\"\ncat \u003c\u003c \"EOF\" \u003e /initdb.d/init.sql\n-- Create the specified database\nCREATE DATABASE IF NOT EXISTS $MYSQL_DATABASE;\n\n-- Create a non-root user and grant privileges\nCREATE USER IF NOT EXISTS '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD';\nGRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO '$MYSQL_USER'@'%';\n\n-- Set the root password\nALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';\n\n-- Flush privileges to apply changes\nFLUSH PRIVILEGES;\nEOF\n\necho \"✅ init.sql created succesfully!\"\n\necho \"======== Starting Mariadb ========\"\n\nexec mysqld --datadir=\"$MARIADB_DATA_DIR\" --user=mysql --init-file=/initdb.d/init.sql\n```\n\n#### Process Breakdown:\n\n1. **Database Creation**:\n   - Creates WordPress database\n   - Uses environment variables\n   - Handles existing database gracefully\n\n2. **User Management**:\n   - Creates application user\n   - Sets secure password\n   - Grants appropriate privileges\n\n3. **Security Setup**:\n   - Limited user privileges\n   - Secure password handling\n   - Proper permission configuration\n\n\u003c!--=====================================\n=         SECURITY MEASURES           =\n======================================--\u003e\n\n## Security Implementation 🔒\n\n1. **Access Control**:\n   - User-based authentication\n   - Role-based privileges\n   - Network-level restrictions\n\n2. **Data Protection**:\n   - File system permissions\n   - Network isolation\n   - Secure configuration\n\n3. **Network Security**:\n   - Backend network isolation\n   - No public exposure\n   - Limited connection access\n\n\u003c!--=====================================\n=         PERFORMANCE TUNING          =\n======================================--\u003e\n\n## Performance Optimization ⚡\n\n1. **Buffer Configuration**:\n   - Optimized buffer pool size\n   - Query cache settings\n   - Connection pool management\n\n2. **Character Set Optimization**:\n   - UTF8MB4 encoding\n   - Proper collation\n   - Index optimization\n\n3. **Connection Management**:\n   - Limited max connections\n   - Connection timeout settings\n   - Thread handling optimization\n\n### Take a look :mag:!\n```bash\ncat /srcs/requirements/mariadb/tools/init.sh\n```\n\nThis MariaDB setup provides a secure, efficient, and reliable database backend for our WordPress installation, ensuring data persistence and optimal performance. 🚀\n\n---\n\n# Bonus Services: Adminer 🎛️\n\n![ADMINER ART](images/adminer-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is Adminer? 📊\nAdminer is a full-featured database management tool written in PHP. In our infrastructure, it provides a lightweight web interface for MariaDB administration, offering a user-friendly alternative to command-line tools.\n\n## Core Features 🎯\n\n1. **Database Management** 💾\n   - Visual query interface and execution\n   - Database structure manipulation\n   - Import/export capabilities\n\n2. **Security Implementation** 🛡️\n   - Secure authentication\n   - HTTPS encryption via NGINX\n   - Network isolation\n\n3. **Integration** 🔌\n   - MariaDB connectivity\n   - NGINX reverse proxy\n   - PHP-FPM processing\n\n## Architecture Benefits 🏗️\n\n- **Lightweight:** Single PHP file, minimal dependencies\n- **Security:** No stored credentials, session-based auth\n- **Interface:** Intuitive design, dark mode support\n\n## Technical Implementation 🔧\n\n### Docker Compose Configuration\n```yaml\nadminer:\n    container_name: adminer\n    image: adminer\n    build:\n      context: ./requirements/bonus/adminer\n    env_file:\n      - .env\n    networks:\n      - backend-db\n      - proxy\n    restart: on-failure\n    depends_on:\n      - mariadb\n    healthcheck:\n      test: [\"CMD\", \"wget\", \"--no-verbose\", \"--spider\", \"http://localhost:8080/\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n```\n\n### Dockerfile Analysis\n```dockerfile\nFROM alpine:3.20\n\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    apache2 \\\n    php82 \\\n    php82-apache2 \\\n    php82-mysqli \\\n    php82-session \\\n    php82-pdo \\\n    php82-pdo_mysql \\\n    mariadb-client \\\n    wget\n\nRUN addgroup -S -g 82 www-data 2\u003e/dev/null || true \u0026\u0026 \\\n    adduser -S -u 82 -D -H -h /var/www -G www-data -g www-data www-data 2\u003e/dev/null || true\n\nRUN mkdir -p /var/www/html /run/apache2\n\nEXPOSE 8080\nCMD [\"/init.sh\"]\n```\n\n### Critical Configurations\n\n1. **Apache Virtual Host**\n```apache\n\u003cVirtualHost *:8080\u003e\n    DocumentRoot /var/www/html\n    \u003cDirectory /var/www/html\u003e\n        Options -Indexes +FollowSymLinks\n        AllowOverride All\n        Require all granted\n    \u003c/Directory\u003e\n\u003c/VirtualHost\u003e\n```\n- Directory listing prevention\n- URL rewriting support\n- Custom port to avoid NGINX conflicts\n\n2. **Security Measures**\n- Non-root execution\n- Restrictive permissions\n- Session-based authentication\n- Network isolation\n\n3. **Process Management**\n```bash\nexec httpd -D FOREGROUND\n```\n- Direct execution\n- Clean signal handling\n- Proper container lifecycle\n\n### Implementation Details\n\n1. **Essential Extensions**\n- PDO for secure connections\n- MySQLi for advanced features\n- Session management support\n\n2. **Health Monitoring**\n```bash\nln -sf /var/www/html/index.php /var/www/html/adminer.php\n```\n- Container health checks\n- Path compatibility\n- Automatic recovery\n\n3. **Logging**\n```apache\nErrorLog /dev/stderr\nCustomLog /dev/stdout combined\n```\n- Docker-friendly logging\n- Real-time monitoring\n\n## Performance Optimization ⚡\n\n- **Apache:** Module optimization, connection pooling\n- **PHP:** Opcode caching, memory limits\n- **Resources:** Minimal dependencies, efficient file serving\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/adminer/tools/init.sh\n```\n\nThis setup provides a secure and efficient database management interface while maintaining optimal performance. 🚀\n\n---\n\n# Bonus Services: Redis ⚡\n\n![REDIS ART](images/redis-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is Redis? 🚀\n\nRedis (Remote Dictionary Server) is an open-source, in-memory data structure store used as a database, cache, message broker, and queue. In our Inception infrastructure, Redis serves as a high-performance caching layer for WordPress, significantly improving response times and reducing database load.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why Redis? 🤔\n\nOur Redis implementation focuses on these key aspects:\n\n1. **Performance Enhancement** 💨\n   - In-memory data storage\n   - WordPress object caching\n   - Session management\n   - Page caching acceleration\n\n2. **Resource Optimization** 🎯\n   - Database load reduction\n   - Memory management with LRU eviction\n   - Connection pooling\n   - Efficient cache invalidation\n\n3. **WordPress Integration** 🔌\n   - Object caching via Redis plugin\n   - PHP extension support\n   - Coordinated cache management\n   - Transient and fragment caching\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Technical Implementation 🔧\n\n### 1. Docker Compose Configuration\n\n```yaml\nredis:\n    container_name: redis\n    image: redis\n    build:\n      context: ./requirements/bonus/redis\n      dockerfile: Dockerfile\n    volumes:\n      - wp-data:/var/www/html\n    networks:\n      - cache\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD\", \"redis-cli\", \"ping\"]\n      interval: 10s\n      timeout: 5s\n      retries: 5\n      start_period: 30s\n```\n\n#### Key Elements:\n\n- Shares WordPress volume for data persistence\n- Isolated in dedicated `cache` network\n- Regular health monitoring via Redis CLI\n- Automatic failure recovery\n\n### 2. Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\nRUN apk update \u0026\u0026 apk add --no-cache redis\n\nCOPY tools/init.sh /init.sh\nRUN chmod +x /init.sh\n\nEXPOSE 6379\n\nENTRYPOINT [\"/init.sh\"]\n\n```\n\nWe configure the redis files in the init.sh script:\n\n```bash\necho \"maxmemory 256mb\" \u003e\u003e /etc/redis.conf\necho \"maxmemory-policy allkeys-lru\" \u003e\u003e /etc/redis.conf\nsed -i 's/^bind 127.0.0.1/#bind 127.0.0.1/' /etc/redis.conf\n\nmkdir -p /data \u0026\u0026 chown redis:redis /data\n\nexec redis-server /etc/redis.conf --protected-mode no\n```\n\n#### Configuration Elements:\n- Memory limit: 256MB with LRU eviction\n- Remote connections enabled\n- Dedicated data directory with proper permissions\n- Protected mode disabled for container environment\n\n\u003c!--=====================================\n=     WORDPRESS INTEGRATION          =\n======================================--\u003e\n\n### 3. WordPress Integration\n\nRedis configuration in wp-config.php:\n\n```php\n/* Redis configuration */\ndefine('WP_REDIS_HOST', '${REDIS_HOST}');\ndefine('WP_REDIS_PORT', ${REDIS_PORT});\ndefine('WP_REDIS_TIMEOUT', 1);\ndefine('WP_REDIS_READ_TIMEOUT', 1);\ndefine('WP_REDIS_DATABASE', 0);\ndefine('WP_CACHE', true);\n\ndefine('WP_REDIS_DISABLE_METRICS', false);\ndefine('WP_REDIS_METRICS_MAX_TIME', 60);\ndefine('WP_REDIS_SELECTIVE_FLUSH', true);\ndefine('WP_REDIS_MAXTTL', 86400);\n```\n\nKey settings:\n- Host and port configuration\n- Timeout management\n- Metrics collection enabled\n- Selective cache flushing\n- 24-hour maximum TTL\n\n\u003c!--=====================================\n=     SECURITY \u0026 PERFORMANCE          =\n======================================--\u003e\n\n## Security and Performance 🛡️\n\n### Security Measures:\n- Network isolation through Docker networks\n- Volume permissions and ownership\n- Memory limits prevent resource exhaustion\n- Internal-only network exposure\n\n### Performance Optimization:\n- Fixed memory limit with LRU eviction\n- Optimized connection handling\n- Selective cache invalidation\n- Efficient key storage and expiration\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/redis/tools/init.sh\n```\n\nThis Redis implementation provides a robust caching solution for WordPress, balancing performance, security, and reliability. 🚀\n\n---\n\n# Bonus Services: FTP/FTPS 📂\n\n![FTP ART](images/ftp-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is VSFTPD? 🚀\n\nVSFTPD (Very Secure FTP Daemon) is a secure and stable FTP server. In our Inception infrastructure, it provides file transfer capabilities for WordPress over FTPS (FTP over SSL/TLS), enabling secure encrypted file uploads and management while maintaining proper permissions and security.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why VSFTPD? 🤔\n\nOur FTP implementation focuses on these key aspects:\n\n1. **File Management** 📁\n   - Encrypted file transfers\n   - WordPress uploads handling\n   - Permission management\n   - User authentication\n\n2. **Security** 🛡️\n   - SSL/TLS encryption\n   - Chroot environment\n   - User isolation\n   - Certificate-based security\n\n3. **WordPress Integration** 🔌\n   - Secure access to WordPress files\n   - Plugin and theme management\n   - Media upload support\n   - Proper ownership coordination\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Technical Implementation 🔧\n\n### 1. Docker Compose Configuration\n\n```yaml\nftp:\n    container_name: ftp\n    image: ftp\n    build:\n      context: ./requirements/bonus/ftp\n      dockerfile: Dockerfile\n    env_file:\n      - .env\n    ports:\n      - \"20:20\"\n      - \"21:21\"\n      - \"21100-21110:21100-21110\"\n    volumes:\n      - wp-data:/var/www/html\n    networks:\n      - proxy\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD\", \"netstat\", \"-ln\", \"|\", \"grep\", \":21\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 30s\n```\n\n#### Key Elements:\n- Exposes FTP control (21) and data (20) ports\n- Passive port range (21100-21110)\n- Shares WordPress volume\n- Network isolation via proxy network\n- Regular health monitoring\n\n### 2. Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\nRUN apk update \u0026\u0026 \\\n    apk add --no-cache \\\n        vsftpd \\\n        shadow \\\n        linux-pam \\\n        bash \\\n        netcat-openbsd \\\n        logrotate \\\n        openssl\n\nRUN mkdir -p /var/log \u0026\u0026 \\\n    mkdir -p /etc/vsftpd \u0026\u0026 \\\n    mkdir -p /var/run/vsftpd \u0026\u0026 \\\n    mkdir -p /etc/ssl/private\n\nWORKDIR /var/www/html\n\nEXPOSE 20 21 21100-21110\n\nENTRYPOINT [\"/init.sh\"]\n```\n\n#### Configuration Elements:\n- VSFTPD installation with SSL support\n- OpenSSL for certificate management\n- Log rotation setup\n- SSL certificate directories\n- Port exposure for FTPS service\n\n### 3. VSFTPD Configuration\n\nThe initialization script configures VSFTPD with SSL/TLS:\n\n```ini\nssl_enable=YES\nallow_anon_ssl=NO\nforce_local_data_ssl=YES\nforce_local_logins_ssl=YES\nssl_tlsv1=YES\nssl_sslv2=NO\nssl_sslv3=NO\nrequire_ssl_reuse=NO\nssl_ciphers=HIGH\nrsa_cert_file=${FTP_SSL_CERTIFICATE}\nrsa_private_key_file=${FTP_SSL_CERTIFICATE_KEY}\nssl_request_cert=NO\n\nlisten=YES\nlisten_port=21\nanonymous_enable=NO\nlocal_enable=YES\nwrite_enable=YES\nlocal_umask=022\n\nchroot_local_user=YES\nallow_writeable_chroot=YES\nhide_ids=YES\n\npasv_enable=YES\npasv_min_port=21100\npasv_max_port=21110\npasv_address=0.0.0.0\n```\n\n### 4. SSL Certificate Management\n\nThe initialization script handles certificate generation:\n\n```bash\nif [ ! -f \"${FTP_SSL_CERTIFICATE}\" ] || [ ! -f \"${FTP_SSL_CERTIFICATE_KEY}\" ]; then\n    echo \"- Generating new SSL certificate...\"\n    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \\\n        -keyout \"${FTP_SSL_CERTIFICATE_KEY}\" \\\n        -out \"${FTP_SSL_CERTIFICATE}\" \\\n        -subj \"/C=IT/ST=Rome/L=Rome/O=42/OU=42/CN=ftp.${DOMAIN_NAME}\"\n    \n    chmod 600 \"${FTP_SSL_CERTIFICATE_KEY}\"\n    chmod 644 \"${FTP_SSL_CERTIFICATE}\"\nfi\n```\n\nKey aspects:\n- Self-signed certificate generation\n- Proper permission setting\n- One-year validity\n- Domain-specific configuration\n\n\u003c!--=====================================\n=     SECURITY \u0026 PERFORMANCE          =\n======================================--\u003e\n\n## Security and Performance 🔒\n\n### Security Measures:\n- SSL/TLS encryption for all connections\n- Self-signed certificate management\n- User chroot jail\n- No anonymous access\n- Secure password handling\n- Limited passive port range\n- Proper file permissions\n- Log rotation setup\n- PAM authentication\n\n### WordPress Integration:\n- SSL-enabled file transfers\n- Coordinated permissions with PHP-FPM\n- Plugin/theme upload support\n- Encrypted data transmission\n- Proper ownership maintenance\n\n### Additional Features:\n- Passive mode support for NAT/firewall compatibility\n- Log rotation for maintenance\n- Health monitoring\n- Automatic recovery\n- Session timeout management\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/ftp/tools/init.sh\n```\n\nThis FTPS implementation provides secure, encrypted file transfer capabilities while maintaining proper integration with WordPress and other services in our infrastructure. 🚀\n\n---\n\n# Bonus Services: Gatsby App 🎨\n\n![GATSBY-APP ART](images/gatsby-app-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is Gatsby? 🚀\n\nGatsby is a React-based framework for building static websites. In our infrastructure, it serves a simple CV-style static page, demonstrating how modern JavaScript applications can be integrated into our containerized environment.\n\n\u003c!--=====================================\n=         CORE BENEFITS               =\n======================================--\u003e\n\n## Why Gatsby? 🤔\n\n1. **Performance** ⚡\n   - Static site generation means faster page loads\n   - Build-time rendering eliminates server-side processing\n   - Automatic code splitting and optimization\n\n2. **Development** 🛠️\n   - React-based components for modern web development\n   - Hot reloading for efficient development workflow\n   - Simple deployment process with static files\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Implementation 🔧\n\n### Docker Configuration\n\n```yaml\ngatsby-app:\n    container_name: gatsby-app\n    image: gatsby-app\n    build: \n      context: ./requirements/bonus/gatsby-app\n      dockerfile: Dockerfile\n    networks:\n      - proxy\n    restart: on-failure\n```\n\n### Node.js Environment Setup\n\n```dockerfile\nFROM alpine:3.20\n\nWORKDIR /app\n\nRUN apk add --no-cache \\\n    nodejs \\\n    npm \\\n    git \\\n    bash \\\n    curl\n\nCOPY package*.json ./\n\nRUN npm install\n\nRUN npm install -g gatsby-cli serve\n\nCOPY . .\n\n# Setup init script\nRUN mv /app/tools/init.sh / \u0026\u0026 \\\n    chmod +x /init.sh \u0026\u0026 \\\n    rm -rf /app/tools\n\nEXPOSE 3000\n\nENTRYPOINT [\"/init.sh\"]\n```\n\n### Key Features\n- Modern JavaScript runtime with Node.js\n- Simple static file serving in production\n- Efficient build process\n- Easy integration with NGINX reverse proxy\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/gatsby-app/tools/init.sh\n```\n\nThis lightweight implementation demonstrates how modern frontend technologies can be effectively containerized and integrated into our infrastructure. 🚀\n\n---\n\n# Bonus Services: Alien Eggs Game 👾\n\n![ALIEN-EGGS ART](images/alien-eggs-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is Alien Eggs? 🎮\n\nAlien Eggs is a custom browser game implementation that showcases containerized game deployment and monitoring. It uses Python's HTTP server capabilities to serve the game files while collecting performance metrics via Prometheus.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Implementation Features 🚀\n\n1. **Python HTTP Server** 🐍\n   - Lightweight server implementation\n   - Static file serving\n   - Cross-Origin handling\n   - Prometheus metrics integration\n\n2. **Monitoring Integration** 📊\n   - Request counting\n   - Active connections tracking\n   - Performance metrics collection\n   - Real-time monitoring\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Technical Setup 🔧\n\n### Docker Configuration\n\n```yaml\nalien-eggs:\n    container_name: alien-eggs\n    image: alien-eggs\n    build:\n      context: ./requirements/bonus/alien-eggs\n      dockerfile: Dockerfile\n    networks:\n      - proxy\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD\", \"wget\", \"--no-verbose\", \"--tries=1\", \"--spider\", \"http://127.0.0.1:8060\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 45s\n```\n\n### Container Setup\n\n```dockerfile\nFROM alpine:3.20\n\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    python3 \\\n    py3-pip \\\n    py3-prometheus-client\n\nWORKDIR /app\n\nCOPY src/ /app/src/\n\nRUN chmod +x /app/src/serve.py\n\nENV DOCKER_CONTAINER=1\nENV PYTHONUNBUFFERED=1\n\nEXPOSE 8060 8000\n\nENTRYPOINT [ \"python3\", \"/app/src/serve.py\" ]\nCMD [\"--root\", \"/app/src\", \"--no-browser\", \"--port\", \"8060\", \"--metrics-port\", \"8000\"]\n```\n\n### Python Server Implementation\n\nKey server features:\n```python\n# Prometheus metrics\nREQUEST_COUNT = Counter(\"http_requests_total\", \"Total HTTP requests served\")\nACTIVE_REQUESTS = Gauge(\"active_http_requests\", \"Number of active HTTP requests\")\n\nclass MetricsRequestHandler(CORSRequestHandler):\n    def do_GET(self):\n        # Track request metrics\n        REQUEST_COUNT.inc()\n        ACTIVE_REQUESTS.inc()\n        try:\n            super().do_GET()\n        finally:\n            ACTIVE_REQUESTS.dec()\n```\n\n\u003c!--=====================================\n=     MONITORING INTEGRATION          =\n======================================--\u003e\n\n## Monitoring Features 📈\n\n### Metrics Collection\n- Total request count tracking\n- Active request gauging\n- Latency measurement\n- Server status monitoring\n\n### Prometheus Integration\n- Metrics exposed on port 8000\n- Custom metrics endpoints\n- Real-time data collection\n- Dashboard visualization support\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/alien-eggs/tools/init.sh\n```\n```bash\ncat /srcs/requirements/bonus/alien-eggs/src/serve.py\n```\n\nThis implementation demonstrates how to integrate a simple game serving with monitoring capabilities, providing insights into server performance and usage patterns. 🎮\n\n---\n\n# Additional Services :chart_with_upwards_trend:\n\n# Monitoring Services: cAdvisor 📊\n\n![CADVISOR ART](images/cadvisor-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is cAdvisor? 🔍\n\ncAdvisor (Container Advisor) is a container monitoring tool that provides resource usage and performance characteristics of running containers. In our infrastructure, it serves as the primary collector of container metrics, feeding data to Prometheus for storage and Grafana for visualization.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why cAdvisor? 🤔\n\n1. **Container Metrics** 📈\n   - CPU usage tracking\n   - Memory consumption monitoring\n   - Network I/O statistics\n   - Storage metrics collection\n\n2. **Docker Integration** 🐳\n   - Native Docker support\n   - Real-time metrics collection\n   - Container label support\n   - Resource usage analysis\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Implementation 🔧\n\n### Docker Compose Configuration\n\n```yaml\ncadvisor:\n    container_name: cadvisor\n    image: cadvisor\n    build:\n      context: ./requirements/bonus/monitoring/cadvisor\n      dockerfile: Dockerfile\n    volumes:\n      - /:/rootfs:ro\n      - /var/run:/var/run:rw\n      - /sys:/sys:ro\n      - /var/lib/docker/:/var/lib/docker:ro\n      - /dev/disk/:/dev/disk:ro\n      - /etc/machine-id:/etc/machine-id:ro\n      - /var/run/docker.sock:/var/run/docker.sock:rw\n    networks:\n      - monitoring\n      - proxy\n    expose:\n      - \"8080\"\n    restart: on-failure\n    privileged: true\n    devices: \n      - \"/dev/kmsg:/dev/kmsg:rw\"\n    group_add:\n      - docker\n    security_opt:\n      - apparmor:unconfined\n    healthcheck:\n      test: [\"CMD\", \"curl\", \"-f\", \"http://localhost:8080/cadvisor/healthz\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 30s\n```\n\n### Key Volume Mounts\n- `/:/rootfs:ro`: Root filesystem access\n- `/var/run:/var/run:rw`: Runtime data access\n- `/sys:/sys:ro`: System information\n- `/var/lib/docker/:/var/lib/docker:ro`: Docker data\n- `/var/run/docker.sock:/var/run/docker.sock:rw`: Docker socket for container metrics\n\n### Container Setup\n\n```dockerfile\nFROM alpine:3.20\n\nENV VERSION=\"v0.49.2\"\n\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    wget \\\n    curl \\\n    shadow \\\n    libc6-compat \\\n    device-mapper \\\n    thin-provisioning-tools \\\n    ca-certificates \\\n    tzdata \\\n    \u0026\u0026 rm -rf /var/cache/apk/*\n\nRUN addgroup -S -g 998 docker \u0026\u0026 \\\n    addgroup -S cadvisor \u0026\u0026 \\\n    adduser -S -G cadvisor cadvisor \u0026\u0026 \\\n    adduser cadvisor docker\n\nRUN mkdir -p /etc/cadvisor \u0026\u0026 \\\n    touch /etc/machine-id \u0026\u0026 \\\n    chmod 644 /etc/machine-id \u0026\u0026 \\\n    chown -R cadvisor:cadvisor /etc/cadvisor \u0026\u0026 \\\n    mkdir -p /var/run/docker \u0026\u0026 \\\n    chown -R root:docker /var/run/docker \u0026\u0026 \\\n    chmod 775 /var/run/docker\n\nRUN wget -O /usr/local/bin/cadvisor \"https://github.com/google/cadvisor/releases/download/${VERSION}/cadvisor-${VERSION}-linux-amd64\" \u0026\u0026 \\\n    chmod +x /usr/local/bin/cadvisor \u0026\u0026 \\\n    chown root:docker /usr/local/bin/cadvisor\n\nCOPY tools/init.sh /init.sh\nRUN chmod +x /init.sh \u0026\u0026 \\\n    chown root:docker /init.sh\n\nEXPOSE 8080\n\nUSER root\n\nENTRYPOINT [\"/init.sh\"]\n```\n\n\u003c!--=====================================\n=     METRICS \u0026 MONITORING            =\n======================================--\u003e\n\n## Metrics Collection 📊\n\n### Core Metrics\n1. **Container Stats**\n   - CPU usage percentage\n   - Memory consumption\n   - Network traffic\n   - Disk I/O\n\n2. **System Information**\n   - Host metrics\n   - Docker stats\n   - Resource limits\n   - Usage trends\n\n### Integration Points\n1. **Prometheus**\n   - Metrics endpoint exposure\n   - Custom metric relabeling\n   - Container identification\n   - Performance data collection\n\n2. **Security Considerations**\n   - Read-only filesystem access\n   - Docker group membership\n   - Privileged mode requirements\n   - Limited network exposure\n\n### Initialization Script\nThe `init.sh` script handles setup and permissions:\n```bash\n#!/bin/sh\nset -e\n\nif [ -S \"/var/run/docker.sock\" ]; then\n    chmod 666 /var/run/docker.sock\n    chown root:docker /var/run/docker.sock\nfi\n\nCADVISOR_OPTS=\"\n  --port=8080 \\\n  --storage_duration=1m \\\n  --housekeeping_interval=10s \\\n  --max_housekeeping_interval=15s \\\n  --global_housekeeping_interval=1m0s \\\n  --disable_metrics=advtcp,cpu_topology,cpuset,hugetlb,memory_numa,process,referenced_memory,resctrl,sched,tcp,udp \\\n  --docker_only=true \\\n  --docker=unix:///var/run/docker.sock \\\n  --allow_dynamic_housekeeping=true \\\n  --url_base_prefix=/cadvisor \\\n  --docker_env_metadata_whitelist=container_name,HOSTNAME\"\n\nexec /usr/local/bin/cadvisor $CADVISOR_OPTS\n```\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/monitoring/cadvisor/tools/init.sh\n```\n\ncAdvisor provides essential container metrics that enable monitoring and analysis of our infrastructure's performance and resource utilization. Its integration with Prometheus and Grafana creates a comprehensive monitoring solution. 🚀\n\n---\n\n# Monitoring Services: Prometheus 📊\n\n![PROMETHEUS ART](images/prometheus-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is Prometheus? 🔍\n\nPrometheus is an open-source systems monitoring and alerting toolkit. In our infrastructure, it serves as the central metrics collection and storage system, gathering data from various services including cAdvisor and our Alien Eggs game.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why Prometheus? 🎯\n\n1. **Metrics Collection** 📈\n   - Pull-based metrics collection\n   - Multi-dimensional data model\n   - Flexible query language (PromQL)\n   - Service discovery support\n\n2. **Integration Points** 🔌\n   - cAdvisor container metrics\n   - Alien Eggs game metrics\n   - Built-in monitoring APIs\n   - Grafana data source\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Implementation 🔧\n\n### Docker Compose Configuration\n\n```yaml\nprometheus:\n    container_name: prometheus\n    image: prometheus\n    build:\n      context: ./requirements/bonus/monitoring/prometheus\n      dockerfile: Dockerfile\n    env_file:\n      - .env\n    volumes:\n      - prometheus-data:/prometheus/data\n    networks:\n      - monitoring\n      - proxy\n    restart: on-failure\n    healthcheck:\n      test: \n        - CMD\n        - wget\n        - --no-verbose\n        - --tries=1\n        - --spider\n        - --auth-no-challenge\n        - --user=admin\n        - --password=${PROMETHEUS_PASSWORD}\n        - http://localhost:9090/-/healthy\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 45s\n```\n\n### Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\n# Install necessary packages\nRUN apk add --no-cache \\\n    wget \\\n    tar \\\n    openssl \\\n    python3 \\\n    py3-bcrypt \\\n    shadow \\\n    curl \\\n    netcat-openbsd\n\n# Create prometheus user and group\nRUN addgroup -S prometheus \u0026\u0026 \\\n    adduser -S -G prometheus -s /sbin/nologin prometheus\n\n# Set up Prometheus\nWORKDIR /prometheus\nRUN wget https://github.com/prometheus/prometheus/releases/download/v3.0.1/prometheus-3.0.1.linux-amd64.tar.gz \u0026\u0026 \\\n    tar -xvzf prometheus-3.0.1.linux-amd64.tar.gz \u0026\u0026 \\\n    mv prometheus-3.0.1.linux-amd64/* . \u0026\u0026 \\\n    rm -rf prometheus-3.0.1.linux-amd64 prometheus-3.0.1.linux-amd64.tar.gz\n\n# Create and configure directories\nRUN mkdir -p /etc/prometheus /prometheus/data \u0026\u0026 \\\n    chown -R prometheus:prometheus /etc/prometheus \u0026\u0026 \\\n    chown -R prometheus:prometheus /prometheus \u0026\u0026 \\\n    chmod -R 775 /prometheus/data \u0026\u0026 \\\n    chmod g+rwx /prometheus/data \u0026\u0026 \\\n    chmod +x /prometheus/prometheus\n\nEXPOSE 9090\n\nUSER prometheus\nWORKDIR /prometheus\n\nENTRYPOINT [\"/init.sh\"]\n```\n\n#### Key Elements:\n1. **Base Image \u0026 Dependencies**\n   - Alpine Linux for minimal footprint\n   - Essential tools for setup and monitoring\n   - Python and bcrypt for password hashing\n\n2. **Security Setup**\n   - Dedicated prometheus user/group\n   - Non-login shell for security\n   - Proper file permissions\n   - User privilege separation\n\n3. **Prometheus Installation**\n   - Direct binary download\n   - Version 3.0.1 specification\n   - Clean installation process\n   - Proper directory structure\n\n4. **Security Hardening**\n   - Non-root user operation\n   - Limited permissions\n   - Proper workspace setup\n   - Custom entrypoint script\n\n### Security Implementation\n\n1. **Basic Authentication**\n```python\nHASHED_PASSWORD=$(python3 -c \"\nimport bcrypt, sys\npassword = '${PROMETHEUS_PASSWORD}'.encode()\nprint(bcrypt.hashpw(password, bcrypt.gensalt(rounds=10)).decode())\n\")\n```\n\n2. **Web Configuration**\n```yaml\nbasic_auth_users:\n  admin: ${HASHED_PASSWORD}\n```\n\n### Metrics Configuration\n\n```yaml\nglobal:\n  scrape_interval: 15s\n  evaluation_interval: 15s\n  scrape_timeout: 10s\n\nscrape_configs:\n  - job_name: 'prometheus'\n    basic_auth:\n      username: 'admin'\n      password: '${PROMETHEUS_PASSWORD}'\n    static_configs:\n      - targets: ['localhost:9090']\n\n  - job_name: 'alien-eggs'\n    metrics_path: '/metrics'\n    static_configs:\n      - targets: ['alien-eggs:8000']\n    metric_relabel_configs:\n      - source_labels: [__name__]\n        regex: '(http_requests_total|active_http_requests)'\n        action: keep\n\n  - job_name: 'cadvisor'\n    scrape_interval: 5s\n    metrics_path: '/cadvisor/metrics'\n    scheme: 'http'\n    static_configs:\n      - targets: ['cadvisor:8080']\n    metric_relabel_configs:\n      - source_labels: [container_label_com_docker_compose_service]\n        target_label: service\n      - source_labels: [container_name]\n        target_label: container\n      - source_labels: [image]\n        target_label: docker_image\n```\n\n\u003c!--=====================================\n=     INITIALIZATION \u0026 SETUP          =\n======================================--\u003e\n\n## Service Setup 🛠️\n\n### Initialization Process\n1. Password hash generation for authentication\n2. Configuration file generation\n3. Metrics endpoints setup\n4. Storage configuration\n\n### Directory Structure\n```bash\n.\n├── /etc/prometheus/     # Configuration files\n│   ├── prometheus.yml   # Main configuration\n│   └── web.yml          # Authentication config\n└── /prometheus/\n    └── data/            # TSDB storage\n```\n\n### Key Features\n- Time series database (TSDB) for metrics storage\n- Basic authentication for security\n- Metric relabeling for better organization\n- Service discovery through static configuration\n\n\u003c!--=====================================\n=     MONITORING INTEGRATION          =\n======================================--\u003e\n\n## Monitoring Integration 📈\n\n### Collected Metrics\n\n1. **Container Metrics** (via cAdvisor)\n   - Resource usage\n   - Performance metrics\n   - Network statistics\n   - Container health\n\n2. **Application Metrics**\n   - HTTP request counts\n   - Active connections\n   - Response times\n   - Custom metrics\n\n### PromQL Examples\n\nMonitor container CPU usage:\n```promql\nsum(rate(container_cpu_usage_seconds_total{container!=\"\"}[1m])) by (container) * 100\n```\n\nTrack HTTP requests:\n```promql\nrate(http_requests_total[5m])\n```\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/monitoring/prometheus/tools/init.sh\n```\n\nThis Prometheus implementation provides robust metrics collection and storage, forming the backbone of our monitoring infrastructure. Its integration with cAdvisor and custom application metrics enables comprehensive system observation. 🚀\n\n---\n\n# Monitoring Services: Grafana 📊\n\n![GRAFANA ART](images/grafana-art.png)\n\n\u003c!--=====================================\n=            INTRODUCTION             =\n======================================--\u003e\n\n## What is Grafana? 📈\n\nGrafana is an open-source analytics and visualization platform. In our infrastructure, it serves as the visualization layer for our monitoring stack, providing dashboards for container metrics and application performance data stored in Prometheus.\n\n\u003c!--=====================================\n=         CORE FUNCTIONALITY          =\n======================================--\u003e\n\n## Why Grafana? 🎯\n\n1. **Data Visualization** 📊\n   - Real-time metric visualization\n   - Customizable dashboards\n   - Multiple data source support\n   - Interactive graph exploration\n\n2. **Monitoring Integration** 🔌\n   - Native Prometheus support\n   - Automatic datasource configuration\n   - Dashboard provisioning\n   - Metric query builder\n\n\u003c!--=====================================\n=     TECHNICAL IMPLEMENTATION        =\n======================================--\u003e\n\n## Implementation 🔧\n\n### Docker Compose Configuration\n\n```yaml\ngrafana:\n    container_name: grafana\n    image: grafana\n    build:\n      context: ./requirements/bonus/monitoring/grafana\n      dockerfile: Dockerfile\n    env_file:\n      - .env\n    volumes:\n      - grafana-data:/var/lib/grafana\n    networks:\n      - monitoring\n      - proxy\n    restart: on-failure\n    healthcheck:\n      test: [\"CMD-SHELL\", \"wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/api/health || exit 1\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n      start_period: 120s\n```\n\n### Dockerfile Analysis\n\n```dockerfile\nFROM alpine:3.20\n\nRUN apk update \u0026\u0026 apk add --no-cache \\\n    grafana \\\n    bash \\\n    curl \\\n    wget \\\n    libc6-compat\n\n# Create directories and set permissions\nRUN mkdir -p /etc/grafana \\\n    /var/lib/grafana \\\n    /var/log/grafana\n\n# Copy dashboard configurations\nCOPY --chown=grafana:grafana dashboards/ /var/lib/grafana/dashboards/\nRUN chown -R grafana:grafana /etc/grafana /var/lib/grafana /var/log/grafana\n\nUSER grafana\nEXPOSE 3000\n```\n\n### Key Configuration Elements\n\n1. **Server Settings**\n```ini\n[server]\nprotocol = http\nhttp_addr = 0.0.0.0\nhttp_port = 3000\ndomain = ${DOMAIN_NAME}\nroot_url = %(protocol)s://%(domain)s/grafana\nserve_from_sub_path = true\n```\n\n2. **Security Configuration**\n```ini\n[security]\nadmin_user = ${GF_SECURITY_ADMIN_USER}\nadmin_password = ${GF_SECURITY_ADMIN_PASSWORD}\nallow_embedding = true\ncookie_secure = true\n```\n\n## Grafana Dashboard Management 📊\n\n### Default Dashboards\nOur setup automatically provisions dashboards from `/var/lib/grafana/dashboards/`, including:\n- Container metrics (CPU, Memory, Network)\n- Application metrics (Request rates, Active connections)\n\n### Adding Custom Dashboards\n\n1. **Prometheus Integration**\nFirst, ensure proper datasource configuration:\n```yaml\ndatasources:\n  - name: Prometheus\n    type: prometheus\n    uid: Prometheus      # This UID is important\n    access: proxy\n    url: http://prometheus:9090\n    isDefault: true\n    version: 1\n    editable: true\n    jsonData:\n      timeInterval: \"5s\"\n      queryTimeout: \"30s\"\n      httpMethod: \"POST\"\n    secureJsonData:\n      basicAuthPassword: \"${PROMETHEUS_PASSWORD}\"\n    basicAuth: true\n    basicAuthUser: \"admin\"\n```\n\n2. **Finding Dashboards**\nWe can browse the [Grafana Dashboard Marketplace](https://grafana.com/grafana/dashboards/) for thousend of pre-built options! But there's a catch... \n\n3. **Handling ${DS_PROMETHEUS} Error** ❌\nWhen importing marketplace dashboards, you might encounter a `Datasource ${DS_PROMETHEUS} was not found` error. Fix it using either method:\n\n   **Method A: Pre-Import Fix**\n   ```bash\n   sed -i 's/${DS_PROMETHEUS}/Prometheus/g' dashboard.json\n   ```\n   - Best for automation\n   - Fixes all panels at once\n   - Suitable for multiple dashboards\n\n   **Method B: GUI Fix**\n   1. Import dashboard normally\n   2. Go to Dashboard Settings → Variables\n   3. Update datasource from `${DS_PROMETHEUS}` to `Prometheus`\n   4. Save changes\n   - Visual approach\n   - Good for quick testing\n   - Immediate feedback\n\nThe error occurs because community dashboards use variable references instead of direct datasource names. Both fixing methods ensure proper Prometheus integration and metric visualization.\n\n\u003c!--=====================================\n=     SECURITY \u0026 MAINTENANCE          =\n======================================--\u003e\n\n## Security and Maintenance 🛡️\n\n### Security Measures\n- Basic authentication required\n- Cookie security enabled\n- Anonymous access disabled\n- User signup disabled\n\n### Data Persistence\n- Grafana data volume for configurations\n- Dashboard state preservation\n- User preferences storage\n- Plugin data persistence\n\nThis Grafana implementation provides a robust visualization layer for our monitoring infrastructure, offering both pre-configured dashboards and the flexibility to add custom visualizations as needed. 🚀\n\n### Take a look 🔍!\n```bash\ncat /srcs/requirements/bonus/monitoring/grafana/tools/init.sh\n```\n\n---\n\n# Conclusion 🎯\n\n## Project Overview\nThe Inception project has been an intensive journey into modern infrastructure development. Through building a complete containerized environment from scratch, we've gained practical experience that extends far beyond basic Docker usage.\n\n## Key Takeaways\n- Mastered container orchestration and service isolation\n- Implemented robust security practices at every layer\n- Built comprehensive monitoring and logging solutions\n- Developed clean, maintainable initialization processes\n\n## Moving Forward\nThese skills form the foundation for tackling complex infrastructure challenges in real-world environments. Each component was crafted to reflect professional standards while maintaining clarity and efficiency.\n\nIf you found this guide helpful in your containerization journey, consider leaving a star 🌟 on the repository. Your support helps the community and might save another developer from talking to their rubber duck for too long! 🦆\n\n---\n\n# A Word from the container abyss 🌌\n\nIn our relentless pursuit of knowledge, we ventured into realms where few mortals dare tread. The Inception project, a name that barely contains the eldritch truths we encountered, forced us to peer beyond the veil of conventional computing.\n\nDeep in the abyssal layers of containerization, we discovered truths that changed us forever. Docker, that ancient technology of unknowable origin, revealed to us secrets of process isolation that mortal minds were perhaps not meant to comprehend. Yet comprehend we did, and our sanity held... mostly.\n\nThe monitoring stack, with its all-seeing eyes, now watches our services with an unblinking gaze. Prometheus, keeper of metrics, storing time series that spiral into infinity. Grafana, the great visualizer, rendering patterns that whisper of truths beyond human understanding.\n\nOur initialization scripts, written in languages older than time itself, now wake slumbering services from their digital chrysalis. Each daemon process, each network connection, a thread in the vast tapestry of our infrastructure.\n\nThe knowledge we gained... it weighs upon us. The ability to create and destroy entire environments with but a single command - such power was not meant for mere mortals. Yet here we stand, containers within containers, services calling to services, in an endless dance of deployment.\n\nShould you find yourself drawn to these forbidden arts, should these arcane configurations prove useful in your own descent into the depths of DevOps, perhaps you might leave a star - a small light in the vast darkness of the repository.\n\nMay your containers be stable, and your deployments clean.\n\n*Ph'nglui mglw'nafh Docker Registry wgah'nagl fhtagn* 🐙\n\n~ In eternal containerization ~\n\n![LOVECRAFT ART](images/lovecraft-art.png)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnihilantropy%2Finception","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnihilantropy%2Finception","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnihilantropy%2Finception/lists"}