├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── imgs ├── Architecture-of-Docker.png ├── Docker-Bridge-Network.jpeg ├── Docker-Components.jpeg ├── Docker-Execution-Environment.jpeg ├── Docker-Storage.jpeg ├── Docker-Workflow.jpeg ├── Linux-Cgroups.jpeg ├── Linux-Container-Architecture-1.jpeg ├── Linux-Process-Namespace.jpeg ├── md.png └── vm_vs_containers.jpg ├── init_docker.sh └── srcs ├── .env ├── docker-compose.yml └── requirements ├── bonus ├── adminer │ └── Dockerfile ├── portainer │ └── Dockerfile ├── redis │ ├── Dockerfile │ └── tools │ │ └── conf.py └── static_web │ ├── Dockerfile │ ├── conf │ └── nginx.conf │ └── tools │ ├── index.html │ ├── script.js │ └── styles.css ├── mariadb ├── Dockerfile ├── conf │ └── 50-server.cnf └── tools │ └── script.py ├── nginx ├── Dockerfile └── conf │ └── nginx.conf └── wordpress ├── Dockerfile ├── conf └── wp-config.php └── tools └── script.py /.gitignore: -------------------------------------------------------------------------------- 1 | .env -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 oumaima-aarabe 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | up: dir 2 | docker compose -f ./srcs/docker-compose.yml up --build 3 | 4 | upd: dir 5 | docker compose -f ./srcs/docker-compose.yml up --build -d 6 | 7 | dir: 8 | @mkdir -p /home/ouaarabe/data 9 | @mkdir -p /home/ouaarabe/data/wordpress 10 | @mkdir -p /home/ouaarabe/data/mariadb 11 | 12 | 13 | down: stop 14 | docker compose -f ./srcs/docker-compose.yml down --rmi all --volumes 15 | sudo rm -rf /home/ouaarabe/data/* 16 | 17 | stop: 18 | docker compose -f ./srcs/docker-compose.yml stop 19 | 20 | c ?= mariadb 21 | restart: 22 | docker restart ${c} 23 | 24 | prune: down 25 | docker system prune -af 26 | 27 | re: prune up 28 | 29 | network: 30 | docker network inspect inception 31 | 32 | exec: 33 | docker exec -it ${c} /bin/bash 34 | 35 | 36 | logs: 37 | cd ./srcs && docker compose logs ${c} 38 | 39 | volumes: 40 | docker volume ls 41 | 42 | v ?= mariadb_vol 43 | volumes_rm: 44 | docker volume rm ${v} 45 | 46 | vinspect: 47 | docker volume inspect ${v} 48 | 49 | .PHONY: up upd down stop restart exec logs prune re network volumes volumes_rm vinspect -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #
42 Cursus Project Inception
2 | 3 |
4 | 5 | 6 | ## Table of Contents 7 | 8 | 1. [Overview](#overview) 9 | 2. [Key Components and Their Roles](#key-components-and-their-roles) 10 | 3. [First Basics 😄](#first-basics-) 11 | - [What Is Virtualization](#what-is-virtualization) 12 | - [What Is a Hypervisor](#what-is-a-hypervisor) 13 | - [What Are VMs](#what-are-vms) 14 | - [What Are Containers](#what-are-containers) 15 | - [VMs vs Containers](#vms-vs-containers) 16 | 4. [Docker](#docker) 17 | - [What is Docker](#what-is-docker) 18 | - [Docker vs LXC](#docker-vs-lxc) 19 | - [Docker Ecosystem](#docker-ecosystem) 20 | - [Docker Technologies](#docker-Technologies) 21 | 7. [Docker Images](#docker-images) 22 | 8. [Docker Compose](#docker-compose) 23 | 9. [Docker Volumes](#docker-volumes) 24 | - [Volumes Overview](#volumes-overview) 25 | - [Types of Volumes](#types-of-volumes) 26 | - [Docker Volume Drivers and Mount Options](#docker-volume-drivers-and-mount-options) 27 | - [Volume Drivers](#volume-drivers) 28 | - [Mount Types](#mount-types) 29 | - [Mount Options](#mount-options) 30 | 10. [The Network](#the-network) 31 | 11. [Project Tips](#project-tips) 32 | 12. [Resources](#resources) 33 | 34 | 35 | 36 | ## Overview 37 | 38 | The **Inception** Project is a sophisticated web infrastructure, all running on the same Docker network, orchestrated using Docker and Docker Compose.NGINX manages incoming web traffic, serving static files directly and forwarding dynamic content requests toPHP-FPM, which processes PHP code fromWordPress.WordPress usesRedis for caching frequently accessed data, enhancing performance by reducing database queries toMariaDB, which handles all content data storage and management. After PHP-FPM processes the request and retrieves data fromRedis andMariaDB, the content is returned toNGINX for delivery to the user. Additionally,NGINX serves aStatic Website for direct content delivery.Adminer provides database management forMariaDB, andPortainer oversees and monitors the Docker containers running these services. Docker volumes ensure persistent storage and efficient data management, all within a unified Docker network that facilitates seamless communication and operation across the entire system. 39 | 40 | 41 | 42 | ## Key Components and Their Roles 43 | 44 | The components of the Inception project are interconnected and managed through Docker Compose, which facilitates the setup and orchestration of the multi-container application. Here’s a breakdown of how the various services are configured to work together: 45 | 46 | | Component | Role | 47 | |--------------------------|------------------------------------------------------------------------------------------------------------------------| 48 | | **NGINX** | Acts as the web server and reverse proxy, handling incoming web requests efficiently. Serves static content and forwards dynamic content requests toPHP-FPM. Optimizes web performance and ensures secure connections through SSL/TLS configuration. | 49 | | **WordPress withPHP-FPM** | Forms the core of the dynamic content management system (CMS).PHP-FPM processes PHP scripts, enablingWordPress to generate dynamic web pages based on user interactions, templates, and plugins. Essential for serving personalized content to users. | 50 | | **MariaDB** | Serves as the relational database management system (RDBMS) forWordPress. Stores all structured data generated byWordPress, including posts, pages, comments, and settings. Ensures data persistence and integrity. | 51 | | **Redis** | Acts as an in-memory data structure store, used as a database, cache, and message broker. EnhancesWordPress performance by caching frequently accessed data, reducing load times, and improving the overall user experience. | 52 | | **Static Website** | Represents a simple website hosted alongside theWordPress site. Demonstrates the capability to serve static content efficiently, showcasing the versatility of theNGINX server in handling different types of web content. | 53 | | **Portainer** | Provides a graphical interface for managing Docker containers, images, networks, and volumes. Simplifies the administration of the Docker environment, making it easier to monitor and manage the infrastructure components. | 54 | | **Adminer** | Introduces a web interface for database management, supporting operations such as viewing and editing databases, tables, and records. ComplementsMariaDB by providing an accessible way to interact with the database directly from a web browser. | 55 | 56 | 57 | 58 | - A custom Docker network named `inception` is created to enable seamless communication between all containers. This network ensures that services can find and communicate with each other using their container names as hostnames. 59 | 60 | - Each component is configured to communicate through the `inception` network, ensuring a cohesive and functional web infrastructure. Docker Compose handles the orchestration, including the creation of networks, volumes, and service dependencies, simplifying the setup and management of the project. 61 | ## 62 | ## First Basics 😄 63 | 64 | 65 | 66 | ### What Is Virtualization 67 | 68 | Virtualization involves creating virtual versions or representations of computing resources—such as servers, storage devices, operating systems (OS), or networks—that are abstracted from the underlying physical hardware. This abstraction allows for greater flexibility, scalability, and agility in managing and deploying resources. Essentially, it lets you run multiple virtual computers on a single physical machine, making it like having several computer-generated computers from one set of hardware and software. 69 | 70 | 71 | ### What Is a Hypervisor 72 | A hypervisor is software that enables the creation and management of virtual computing environments. It acts as a lightweight layer, either software or firmware, that sits between the physical hardware and the virtualized environments. This layer allows multiple operating systems to run concurrently on a single physical machine by abstracting and partitioning the underlying hardware resources—such as CPUs, memory, storage, and networking—and allocating them to the virtual environments. Essentially, the hypervisor serves as the middleman, channeling resources from your physical infrastructure to various virtual instances. 73 | Hypervisors are crucial to virtualization technology, enabling efficient utilization and management of computing resources. 74 | 75 | ### What Are VMs 76 | Virtual machines (VMs) are simulated computing environments that run on physical hardware. They enable multiple operating systems and applications to operate independently on a single physical server. Each VM functions as a separate computer, with its own operating system, resources (such as CPU, memory, and storage), and applications. VMs allow for efficient use of hardware resources, simplify system management, and provide increased flexibility in deployment and scalability. 77 | 78 | 79 | ### What are Containers 80 | - `Containers` are a form of virtualization that allows you to run applications in isolated environments. They package an application and its dependencies into a single unit that can run consistently across various computing environments. This ensures that the application will work the same way regardless of where it's deployed. 81 | 82 | - Containers leverage several key Linux features to provide isolation and resource management. Here are the main features: 83 | - Namespaces: These provide process isolation by creating separate environments for containers. Each container gets its own namespace for different aspects: 84 | 85 | - PID Namespace: Isolates process IDs, so processes in one container cannot see or interact with processes in another. 86 | - Network Namespace: Provides each container with its own network stack, including IP addresses and network interfaces. 87 | - Mount Namespace: Isolates the file system, so containers have their own views of the filesystem, independent of the host. 88 | - UTS Namespace: Isolates hostname and domain name settings, allowing containers to have their own hostname. 89 | - IPC Namespace: Isolates inter-process communication resources, such as shared memory segments. 90 | - User Namespace: Allows containers to have their own user and group IDs, enhancing security by mapping container users to different IDs on the host. 91 | - Control Groups (cgroups): Manage and limit the resources allocated to containers. They provide mechanisms to: 92 | 93 | - Limit Resource Usage: Set limits on CPU, memory, disk I/O, and network bandwidth for containers. 94 | - Monitor Resource Usage: Track and report resource usage to manage and optimize performance. 95 | - Filesystem Layers: Containers use layered filesystems to build images. Each layer represents a set of changes (e.g., added files or modified configurations), and these layers are stacked to create a complete image. This allows for efficient storage and sharing of common layers across different containers. 96 | 97 | - Container Runtime: Manages the lifecycle of containers, including starting, stopping, and monitoring. Examples include Docker and containerd. The runtime interacts with namespaces, cgroups, and filesystems to provide container functionality. 98 | 99 | These features work together to provide the isolation, resource management, and efficiency that containers are known for. 100 | 101 | 102 | 103 | ### VMs Vs Containers 104 | 105 | | **Aspect** | **Virtual Machines (VMs)** | **Containers** | 106 | |-----------------------------|---------------------------------------------------------------|------------------------------------------------------------| 107 | | **OS** | Full OS (includes application and dependencies) | Shares host OS kernel (includes only application and dependencies) | 108 | | **Isolation** | Strong isolation, each VM is a separate environment | Moderate isolation, containers share the same OS kernel | 109 | | **Resource Usage** | More resource-intensive, needs separate OS for each VM | Lightweight, uses fewer resources | 110 | | **Boot Time** | Longer boot time due to full OS initialization | Fast startup, often in seconds | 111 | | **Use Cases** | Suitable for running different OS or strong isolation needs | Ideal for microservices, CI/CD, and scalable applications | 112 | 113 | 114 | # Docker 115 | ## What is Docker 116 | 117 | 118 | - `Docker` provides a comprehensive platform and suite of tools that have transformed the way applications are developed, shipped, and run. Built on the concept of containerization, Docker encapsulates applications and their dependencies into self-sufficient containers. This approach ensures that applications run consistently across different environments, from development to production. Docker simplifies container creation, management, and orchestration, making it accessible to developers and operations teams. 119 | 120 | - Before Docker evolved to developing its own container runtime, libcontainer, which now powers Docker containers; Docker utilized LXC to provide an easier way to create , deploy and run applications using containers. Offering a lighter, faster, and more agile way of handling applications , Docker sets the standard for modern application deployment and management. 121 | 122 | 123 | 124 | ## Docker Vs LXC 125 | 126 | | **Aspect** | **LXC** | **Docker** | 127 | |----------------------------|---------------------------------------------------------|-------------------------------------------------------| 128 | | **Container Format** | Varies widely; no standard format | Standardized format with Docker images and Dockerfiles | 129 | | **Ease of Use** | More complex setup requiring detailed OS configuration knowledge | Simplified setup with pre-built packages and extensive documentation. | 130 | | **Portability** | Challenging to ensure consistency across environments | "Build once, run anywhere" consistency | 131 | | **Ecosystem** | Fragmented tools; different solutions for building, sharing, and orchestrating | Comprehensive ecosystem: Docker Hub, Docker Compose, Docker Swarm, Kubernetes | 132 | | **Layered Filesystem** | Often included redundant data; updates could be cumbersome | Layered filesystem for efficient storage and faster builds | 133 | | **Isolation and Security** | Varies; manual configuration required | Improved isolation with integrated namespaces and cgroups in a cohesive platform that abstracts their complexity which is secure by default | 134 | | **Use Cases** | Efficient access to hardware resources, Virtual Desktop Infrastructure (VDI) | Streamlined deployment, Microservices architecture, CI/CD pipelines, Extensive image repository and configuration management | 135 | 136 | 137 | ## Docker ecosystem : 138 | 139 | | **Component** | **Description** | 140 | |---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| 141 | | **Docker Desktop** | Known for its user-friendly interface, Docker Desktop simplifies tasks in building, running, and managing containers. | 142 | | **Docker Engine** | The core runtime component of Docker shipped in Docker Desktop provides a lightweight and secure environment for running containerized applications. | 143 | | **Docker Scout** | Delivers near real-time actionable insights, making it simple to secure and manage the software supply chain end-to-end. | 144 | | **Docker Hub** | The world’s largest and most widely used image repository, Docker Hub serves as the go-to container registry for developers to share and manage containerized applications securely. | 145 | | **Docker Build Cloud** | A premium service that enhances the image-building process in enterprise environments. | 146 | 147 | ## Some Docker technologies: 148 | 149 | 150 | ### The Runtime: 151 | - The runtime is the component that actually runs the containers. It manages the execution and isolation of containers, ensuring they run as lightweight, standalone units. 152 | 153 | ### The Daemon: 154 | - The Docker daemon (or engine) is the core service that runs in the background and manages all Docker objects, including containers, images, networks, and volumes. It listens for Docker API requests and performs actions to manage your containers. 155 | 156 | ### The Orchestrator: 157 | - Tools like Docker Swarm or Kubernetes fall under this category. They manage and coordinate the deployment, scaling, and operations of containerized applications across multiple hosts, ensuring high availability and efficient resource utilization. 158 | 159 | ### The CLI (Command Line Interface): 160 | - The Docker CLI is the command-line tool that allows users to interact with the Docker daemon. It provides commands to build, run, and manage containers, images, networks, and volumes. 161 | 162 | ### The Builder: 163 | - The builder is responsible for creating Docker images from Dockerfiles. It packages applications and their dependencies into a portable image format that can be shared and deployed across different environments. 164 | 165 | ### The Registry: 166 | - A registry is a storage and distribution system for Docker images. Docker Hub is the most well-known registry, but private registries can also be set up. Registries store Docker images and allow them to be retrieved by other users or systems. 167 | 168 | 169 | ## Docker Images 170 | 171 | Simply, Docker images encapsulate everything needed to run an application in a container. They are built from Dockerfiles, stored in registries, and versioned for easy management and distribution. The immutability of images ensures consistency across different environments, making them a crucial part of the Docker containerization ecosystem. 172 | 173 | Docker images are the basis of containers. They are read-only templates with instructions for creating a Docker container. An image is a lightweight, standalone, and executable package that includes everything needed to run a piece of software, such as code, runtime, libraries, environment variables, and configuration files. An image typically contains a union of layered filesystems stacked on top of each other. 174 | 175 | ### Components: 176 | 177 | - Base Image: The starting point for creating a Docker image, typically an operating system or a minimal image with essential packages. 178 | - Layers: Images are built in layers. Each layer represents a set of changes (like added files or configurations) on top of the previous layer. Layers are cached, making subsequent builds faster. 179 | - Dockerfile: A text file with a series of instructions used to build a Docker image. It specifies the base image, adds files, sets environment variables, and defines commands to run. 180 | 181 | ## Docker Compose: 182 | 183 | Docker Compose is a tool for defining and running multi-container Docker applications. It uses a simple YAML file `docker-compose.yml` to configure application services, networks, and volumes, enabling the orchestration of complex applications with a single command. 184 | 185 | ### key Commands: 186 | 187 | `docker-compose up`: Starts all services defined in the `docker-compose.yml` file. It creates containers, networks, and volumes as specified. 188 | `docker-compose down`: Stops and removes all containers, networks, and volumes created by docker-compose up. 189 | `docker-compose build`: Builds or rebuilds the services defined in the Compose file, using the Dockerfile specified for each service. 190 | `docker-compose logs`: Displays logs from the running services, helping with debugging and monitoring. 191 | 192 | ## Docker Volumes: 193 | 194 | ### Volumes Overview 195 | - Volumes are Docker’s method for persisting data generated by and used by Docker containers. Volumes allow data to be shared between containers and retained across container restarts and lifecycles, providing a reliable way to manage persistent storage. 196 | 197 | - You can manage volumes using Docker CLI commands. Here are some examples: 198 | **Create a volume**:` docker volume create my-vol` 199 | **List volumes**: `docker volume ls` 200 | **Inspect a volume**: `docker volume inspect my-vol` 201 | **Remove a volume**: `docker volume rm my-vol` 202 | 203 | ### Types of Volumes: 204 | - There are three types of volumes: host, anonymous, and named: 205 | - A **host volume** lives on the Docker host's filesystem and can be accessed from within the container. 206 | - A **named volume** is a volume which Docker manages where on disk the volume is created, but it is given a name. 207 | - An **anonymous volume** is similar to a named volume, however, it can be difficult to refer to the same volume over time when it is an anonymous volume. Docker handles where the files are stored. 208 | 209 | 210 | - In Docker, managing volumes and other storage options involves various drivers and mount types that determine how data is handled and where it's stored 211 | 212 | 213 | 214 | ### Docker Volume Drivers and Mount Options 215 | 216 | #### Volume Drivers 217 | 218 | | **Driver** | **Description** | **Usage** | 219 | |-----------------|----------------------------------------------------------------------------------------------------------|---------------------------------------------------| 220 | | **Default (local)** | Stores data on the host filesystem. It is the default driver for volumes. | `docker volume create my_volume` | 221 | | **Custom Drivers** | Third-party or custom drivers for advanced features like cloud storage or networked file systems. | `docker volume create --driver custom_driver my_volume` | 222 | 223 | #### Mount Types 224 | 225 | | **Mount Type** | **Description** | **Usage** | 226 | |----------------|----------------------------------------------------------------------------------------------------------|---------------------------------------------------| 227 | | **Volume Mounts** | Mounts a Docker volume into a container, managed by Docker. | `docker run -v my_volume:/path/in/container my_image` | 228 | | **Bind Mounts** | Mounts a specific directory or file from the host filesystem into a container. bypassing Docker’s storage system and granting direct access to host files | `docker run -v /host/path:/container/path my_image` | 229 | | **Tmpfs Mounts** | Creates a temporary filesystem in memory for a container. Data is lost when the container stops. | `docker run --tmpfs /container/path:rw,size=100m my_image` | 230 | 231 | #### Mount Options 232 | 233 | | **Option** | **Description** | **Usage** | 234 | |-----------------|----------------------------------------------------------------------------------------------------------|---------------------------------------------------| 235 | | **Read-Only** | Mounts the volume or bind mount as read-only. | `docker run -v my_volume:/path/in/container:ro my_image` | 236 | | **Read-Write** | Allows both read and write access to the mounted volume or bind mount (default mode). | `docker run -v my_volume:/path/in/container my_image` | 237 | | **Consistency** | Specifies synchronization requirements (for certain drivers), such as `consistent`, `cached`, or `delegated`. | `docker run -v /host/path:/container/path:consistent my_image` | 238 | 239 | 240 | 241 | ## The Network 242 | - Docker's networking capabilities allow containers to communicate with each other and with external systems. Docker supports various network drivers and configurations to facilitate container connectivity. 243 | 244 | - In Docker, networking subsystem is pluggable, using drivers. Several drivers exist by default, and provide core networking functionality: 245 | 246 | 247 | 248 | 249 | | **Network Driver** | **Description** | 250 | |--------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 251 | | **Bridge** | The default network driver. If no driver is specified, this type of network is created. Bridge networks are used when containers on the same host need to communicate with each other. | 252 | | **Host** | Removes network isolation between the container and the Docker host, allowing the container to use the host's networking directly. | 253 | | **Overlay** | Connects multiple Docker daemons and enables communication across nodes for Swarm services and containers. This eliminates the need for OS-level routing. | 254 | | **IPvlan** | Provides control over both IPv4 and IPv6 addressing. The VLAN driver extends this by offering layer 2 VLAN tagging and L3 routing for integration with underlay networks. | 255 | | **Macvlan** | Allows assignment of a MAC address to a container, making it appear as a physical device on the network. Useful for legacy applications that need direct network access. | 256 | | **None** | Completely isolates a container from the host and other containers. This driver is not available for Swarm services. A | 257 | 258 | 259 | 260 | 261 | 262 | ## Project Tips 263 | 264 | 265 | ### Docker Installation for MacOS 266 | 267 | Docker Desktop for Mac allows you to easily run Docker and Kubernetes on your macOS system. It functions within a lightweight Linux VM, which means that while Docker commands will work as expected, only Linux-based Docker containers are supported. To install, search for "install Docker Desktop," download the installer, and follow the on-screen instructions. You can choose between stable and edge channels for feature updates. After installation, launch Docker Desktop from the Launchpad and run Docker commands in the terminal as usual. Note that the Docker client runs natively on macOS, but the Docker daemon operates within the Linux VM. 268 | 269 | For 42 Student you can run the script ./init_docker.sh inside this repo https://github.com/alexandregv/42toolbox.git to use docker in goinfre! 270 | 271 | ### Docker Installation for Linux 272 | 273 | To install Docker on a Linux system, follow these steps: 274 | 275 | 1. **Update your existing list of packages:** 276 | ```bash 277 | sudo apt update 278 | 2. **Install a few prerequisite packages which let apt use packages over HTTPS:** 279 | ```bash 280 | sudo apt install apt-transport-https ca-certificates curl software-properties-common 281 | 3.Add the GPG key for the official Docker repository to your system: 282 | 283 | ```bash 284 | curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - 285 | ``` 286 | 4.Add the Docker repository to APT sources: 287 | 288 | ```bash 289 | sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" 290 | 291 | ``` 292 | 5.Update the package database with Docker packages from the newly added repo: 293 | ```bash 294 | sudo apt update 295 | ```` 296 | 6.Install Docker: 297 | 298 | ```bash 299 | sudo apt install docker 300 | ``` 301 | 302 | ### Adding Domain Name to Hosts File 303 | Adding your domain name to the hosts file allows your local machine to resolve the domain to the specified IP address, which is useful for development and testing purposes. This ensures that when you enter the domain in your browser, it directs to your local server instead of the live site. 304 | 305 | 306 | To add the domain name of the WordPress website to the hosts file, follow these steps: 307 | 308 | 1. **Open the hosts file in a text editor with sudo privileges:** 309 | ```bash 310 | sudo nano /etc/hosts 311 | 312 | 2.**Add a new entry for your domain:** 313 | ```bash 314 | 127.0.0.1 login.42.fr 315 | ``` 316 | 3.**Save and close file :D** 317 | 318 | ## Resources 319 | 320 | - [VM vs Containers: Understanding the Differences](https://www.backblaze.com/blog/vm-vs-containers/) 321 | - [What Are Containers Made From? Kubernetes Story](https://faun.pub/kubernetes-story-linux-namespaces-and-cgroups-what-are-containers-made-from-d544ac9bd622) 322 | - [Understanding Docker Containers: Leveraging Linux Kernels, Namespaces, and Cgroups](https://dev.to/mochafreddo/understanding-docker-containers-leveraging-linux-kernels-namespaces-and-cgroups-4fkk) 323 | - [LXC vs Docker: What’s the Difference?](https://www.docker.com/blog/lxc-vs-docker/#:~:text=Docker%20is%20designed%20for%20developers,the%20operating%20system%20and%20hardware.) 324 | - [The Evolution of Docker Containers](https://www.baeldung.com/linux/docker-containers-evolution) 325 | - [Docker Documentation](https://docs.docker.com/) 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | -------------------------------------------------------------------------------- /imgs/Architecture-of-Docker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Architecture-of-Docker.png -------------------------------------------------------------------------------- /imgs/Docker-Bridge-Network.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Docker-Bridge-Network.jpeg -------------------------------------------------------------------------------- /imgs/Docker-Components.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Docker-Components.jpeg -------------------------------------------------------------------------------- /imgs/Docker-Execution-Environment.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Docker-Execution-Environment.jpeg -------------------------------------------------------------------------------- /imgs/Docker-Storage.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Docker-Storage.jpeg -------------------------------------------------------------------------------- /imgs/Docker-Workflow.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Docker-Workflow.jpeg -------------------------------------------------------------------------------- /imgs/Linux-Cgroups.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Linux-Cgroups.jpeg -------------------------------------------------------------------------------- /imgs/Linux-Container-Architecture-1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Linux-Container-Architecture-1.jpeg -------------------------------------------------------------------------------- /imgs/Linux-Process-Namespace.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/Linux-Process-Namespace.jpeg -------------------------------------------------------------------------------- /imgs/md.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/md.png -------------------------------------------------------------------------------- /imgs/vm_vs_containers.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oumaima-aarabe/inception/2b13653af5a10d9d188abb15b458d51a620e30b8/imgs/vm_vs_containers.jpg -------------------------------------------------------------------------------- /init_docker.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # **************************************************************************** # 3 | # # 4 | # ::: :::::::: # 5 | # init_docker.sh :+: :+: :+: # 6 | # +:+ +:+ +:+ # 7 | # By: aguiot-- +#+ +:+ +#+ # 8 | # +#+#+#+#+#+ +#+ # 9 | # Created: 2019/11/18 08:17:08 by aguiot-- #+# #+# # 10 | # Updated: 2020/02/20 14:00:32 by aguiot-- ### ########.fr # 11 | # Updated: 2020/02/20 14:34:42 by aguiot-- ### ########.fr # 12 | # # 13 | # **************************************************************************** # 14 | 15 | # https://github.com/alexandregv/42toolbox 16 | 17 | # Ensure USER variabe is set 18 | [ -z "${USER}" ] && export USER=$(whoami) 19 | 20 | ################################################################################ 21 | 22 | # Config 23 | docker_destination="/goinfre/$USER/docker" #=> Select docker destination (goinfre is a good choice) 24 | 25 | ################################################################################ 26 | 27 | # Colors 28 | blue=$'\033[0;34m' 29 | cyan=$'\033[1;96m' 30 | reset=$'\033[0;39m' 31 | 32 | # Uninstall docker, docker-compose and docker-machine if they are installed with brew 33 | brew uninstall -f docker docker-compose docker-machine &>/dev/null ;: 34 | 35 | # Check if Docker is installed with MSC and open MSC if not 36 | if [ ! -d "/Applications/Docker.app" ] && [ ! -d "~/Applications/Docker.app" ]; then 37 | echo "${blue}Please install ${cyan}Docker for Mac ${blue}from the MSC (Managed Software Center)${reset}" 38 | open -a "Managed Software Center" 39 | read -n1 -p "${blue}Press RETURN when you have successfully installed ${cyan}Docker for Mac${blue}...${reset}" 40 | echo "" 41 | fi 42 | 43 | # Kill Docker if started, so it doesn't create files during the process 44 | pkill Docker 45 | 46 | # Ask to reset destination if it already exists 47 | if [ -d "$docker_destination" ]; then 48 | read -n1 -p "${blue}Folder ${cyan}$docker_destination${blue} already exists, do you want to reset it? [y/${cyan}N${blue}]${reset} " input 49 | echo "" 50 | if [ -n "$input" ] && [ "$input" = "y" ]; then 51 | rm -rf "$docker_destination"/{com.docker.{docker,helper},.docker} &>/dev/null ;: 52 | fi 53 | fi 54 | 55 | # Unlinks all symlinks, if they are 56 | unlink ~/Library/Containers/com.docker.docker &>/dev/null ;: 57 | unlink ~/Library/Containers/com.docker.helper &>/dev/null ;: 58 | unlink ~/.docker &>/dev/null ;: 59 | 60 | # Delete directories if they were not symlinks 61 | rm -rf ~/Library/Containers/com.docker.{docker,helper} ~/.docker &>/dev/null ;: 62 | 63 | # Create destination directories in case they don't already exist 64 | mkdir -p "$docker_destination"/{com.docker.{docker,helper},.docker} 65 | 66 | # Make symlinks 67 | ln -sf "$docker_destination"/com.docker.docker ~/Library/Containers/com.docker.docker 68 | ln -sf "$docker_destination"/com.docker.helper ~/Library/Containers/com.docker.helper 69 | ln -sf "$docker_destination"/.docker ~/.docker 70 | 71 | # Start Docker for Mac 72 | open -g -a Docker 73 | 74 | echo "${cyan}Docker${blue} is now starting! Please report any bug to: ${cyan}aguiot--${reset}" -------------------------------------------------------------------------------- /srcs/.env: -------------------------------------------------------------------------------- 1 | MYSQL_DATABASE_NAME=wp_db 2 | MYSQL_USER=wordpress_user 3 | MYSQL_PASSWORD=wordpress_password 4 | MYSQL_ROOT_PASSWORD=rootpassword 5 | 6 | WP_ADMIN_USER=ouaarabe 7 | WP_ADMIN_PASSWORD=randompass 8 | WP_ADMIN_MAIL=contact@ouaarabe.com 9 | WP_URL=ouaarabe.42.fr 10 | 11 | WP_USER=bota 12 | WP_USER_PSWD=guestpass 13 | WP_USER_MAIL=oumi@example.com 14 | -------------------------------------------------------------------------------- /srcs/docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | nginx: 3 | build: requirements/nginx/ 4 | image: nginx:ouaarabe 5 | container_name: nginx 6 | ports: 7 | - "443:443" 8 | depends_on: 9 | - wordpress 10 | volumes: 11 | - wp_vol:/var/www/html 12 | networks: 13 | - inception 14 | restart: on-failure 15 | 16 | wordpress: 17 | build: requirements/wordpress/ 18 | image: wp:ouaarabe 19 | container_name: wordpress 20 | expose: 21 | - "9000" 22 | volumes: 23 | - wp_vol:/var/www/html 24 | depends_on: 25 | - mariadb 26 | networks: 27 | - inception 28 | env_file: 29 | - .env 30 | restart: on-failure 31 | 32 | mariadb: 33 | build: requirements/mariadb/ 34 | image: mariadb:ouaarabe 35 | container_name: mariadb 36 | expose: 37 | - "3306" 38 | env_file: 39 | - .env 40 | volumes: 41 | - mariadb_vol:/var/lib/mysql 42 | networks: 43 | - inception 44 | restart : on-failure 45 | 46 | redis: 47 | build: requirements/bonus/redis/ 48 | image: redis:ouaarabe 49 | container_name: redis 50 | depends_on: 51 | - wordpress 52 | expose: 53 | - "6379" 54 | networks: 55 | - inception 56 | restart: on-failure 57 | 58 | adminer: 59 | build: requirements/bonus/adminer/ 60 | image: adminer:ouaarabe 61 | container_name: adminer 62 | depends_on: 63 | - mariadb 64 | ports: 65 | - "8081:8081" 66 | networks: 67 | - inception 68 | restart: on-failure 69 | 70 | static_web: 71 | build: requirements/bonus/static_web/ 72 | image: static_web:ouaarabe 73 | container_name: static_web 74 | ports: 75 | - "8080:8080" 76 | networks: 77 | - inception 78 | restart: on-failure 79 | 80 | portainer: 81 | build: requirements/bonus/portainer/ 82 | image: portainer:ouaarabe 83 | container_name: portainer 84 | ports: 85 | - "1234:9000" 86 | volumes: 87 | - /var/run/docker.sock:/var/run/docker.sock 88 | networks: 89 | - inception 90 | restart: on-failure 91 | 92 | volumes: 93 | wp_vol: 94 | name : wp_vol 95 | driver: local 96 | driver_opts: 97 | type: 'none' 98 | o: bind 99 | device: /home/ouaarabe/data/wordpress 100 | 101 | mariadb_vol: 102 | name: mariadb_vol 103 | driver: local 104 | driver_opts: 105 | type: 'none' 106 | o: bind 107 | device: /home/ouaarabe/data/mariadb 108 | 109 | networks: 110 | inception: 111 | name: inception 112 | driver: bridge 113 | 114 | -------------------------------------------------------------------------------- /srcs/requirements/bonus/adminer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | RUN apt-get update && apt-get install -y --no-install-recommends \ 4 | wget php php-mysqli \ 5 | && apt-get clean \ 6 | && rm -rf /var/lib/apt/lists/* 7 | 8 | WORKDIR /var/www 9 | 10 | RUN wget --no-check-certificate https://www.adminer.org/latest.php -O adminer.php 11 | 12 | RUN mv adminer.php index.php 13 | 14 | CMD ["php", "-S", "0.0.0.0:8081"] -------------------------------------------------------------------------------- /srcs/requirements/bonus/portainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | RUN apt-get update && apt-get install -y curl 4 | 5 | RUN curl -L https://github.com/portainer/portainer/releases/download/2.19.5/portainer-2.19.5-linux-amd64.tar.gz -o portainer.tar.gz && tar -xzvf portainer.tar.gz && rm portainer.tar.gz 6 | 7 | CMD ["/portainer/portainer"] -------------------------------------------------------------------------------- /srcs/requirements/bonus/redis/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | # Update and Install Redis 4 | RUN apt-get update && apt-get upgrade -y && \ 5 | apt-get install -y redis-server && \ 6 | apt-get install -y python3 7 | 8 | # # Expose Redis port 9 | 10 | COPY ./tools/conf.py / 11 | ENTRYPOINT [ "python3", "/conf.py"] 12 | 13 | 14 | #docker exec -it redis redis-cli monitor 15 | # Bind Address: Set to 127.0.0.1 to ensure Redis only listens on the localhost, enhancing security. 16 | # Max Memory: Limited to 20mb to control Redis's memory usage and prevent it from consuming excessive system resources. 17 | # Max Memory Policy: Set to allkeys-lru to specify the eviction strategy when the memory limit is reached, favoring the removal of less recently used keys. -------------------------------------------------------------------------------- /srcs/requirements/bonus/redis/tools/conf.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | subprocess.run(['sed', '-i', 's|# maxmemory |maxmemory 20mb|g', '/etc/redis/redis.conf']) 4 | 5 | line = 'maxmemory-policy allkeys-lru' 6 | with open('/etc/redis/redis.conf', 'r') as file: 7 | lines = file.readlines() 8 | if line not in lines: 9 | with open('/etc/redis/redis.conf', 'a') as file: 10 | file.write(line + '\n') 11 | subprocess.run(["redis-server", "--protected-mode", "no"]) 12 | -------------------------------------------------------------------------------- /srcs/requirements/bonus/static_web/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | RUN apt-get -y update && apt-get -y upgrade && apt-get install -y nginx 4 | 5 | COPY ./conf/nginx.conf /etc/nginx/sites-enabled/default 6 | 7 | COPY ./tools/ /var/www/html/ 8 | 9 | CMD ["nginx", "-g", "daemon off;"] 10 | 11 | -------------------------------------------------------------------------------- /srcs/requirements/bonus/static_web/conf/nginx.conf: -------------------------------------------------------------------------------- 1 | server { 2 | 3 | listen 8080; 4 | 5 | root /var/www/html/; 6 | index index.html; 7 | 8 | } -------------------------------------------------------------------------------- /srcs/requirements/bonus/static_web/tools/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 42 Cursus Project Inception 7 | 8 | 9 | 10 |
11 |

42 Cursus Project Inception

12 |
13 | 14 | 31 | 32 |
33 |
34 |

Overview

35 |

The Inception Project is a sophisticated web infrastructure, all running on the same Docker network, orchestrated using Docker and Docker Compose.

36 |

NGINX manages incoming web traffic, serving static files directly and forwarding dynamic content requests to PHP-FPM, which processes PHP code from WordPress. WordPress uses Redis for caching frequently accessed data, enhancing performance by reducing database queries to MariaDB, which handles all content data storage and management. After PHP-FPM processes the request and retrieves data from Redis and MariaDB, the content is returned to NGINX for delivery to the user. Additionally, NGINX serves a Static Website for direct content delivery. Adminer provides database management for MariaDB, and Portainer oversees and monitors the Docker containers running these services. Docker volumes ensure persistent storage and efficient data management, all within a unified Docker network that facilitates seamless communication and operation across the entire system.

37 |
38 | 39 |
40 |

Key Components and Their Roles

41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 |
ComponentRole
NGINXActs as the web server and reverse proxy, handling incoming web requests efficiently. Serves static content and forwards dynamic content requests to PHP-FPM. Optimizes web performance and ensures secure connections through SSL/TLS configuration.
WordPress with PHP-FPMForms the core of the dynamic content management system (CMS). PHP-FPM processes PHP scripts, enabling WordPress to generate dynamic web pages based on user interactions, templates, and plugins. Essential for serving personalized content to users.
MariaDBServes as the relational database management system (RDBMS) for WordPress. Stores all structured data generated by WordPress, including posts, pages, comments, and settings. Ensures data persistence and integrity.
RedisActs as an in-memory data structure store, used as a database, cache, and message broker. Enhances WordPress performance by caching frequently accessed data, reducing load times, and improving the overall user experience.
Static WebsiteRepresents a simple website hosted alongside the WordPress site. Demonstrates the capability to serve static content efficiently, showcasing the versatility of the NGINX server in handling different types of web content.
PortainerProvides a graphical interface for managing Docker containers, images, networks, and volumes. Simplifies the administration of the Docker environment, making it easier to monitor and manage the infrastructure components.
AdminerIntroduces a web interface for database management, supporting operations such as viewing and editing databases, tables, and records. Complements MariaDB by providing an accessible way to interact with the database directly from a web browser.
75 |
76 | 77 |
78 |

First Basics 😄

79 |

What Is Virtualization

80 |

Virtualization involves creating virtual versions or representations of computing resources—such as servers, storage devices, operating systems (OS), or networks—that are abstracted from the underlying physical hardware. This abstraction allows for greater flexibility, scalability, and agility in managing and deploying resources. Essentially, it lets you run multiple virtual computers on a single physical machine, making it like having several computer-generated computers from one set of hardware and software.

81 | 82 |

What Is a Hypervisor

83 |

A hypervisor is software that enables the creation and management of virtual computing environments. It acts as a lightweight layer, either software or firmware, that sits between the physical hardware and the virtualized environments. This layer allows multiple operating systems to run concurrently on a single physical machine by abstracting and partitioning the underlying hardware resources—such as CPUs, memory, storage, and networking—and allocating them to the virtual environments. Essentially, the hypervisor serves as the middleman, channeling resources from your physical infrastructure to various virtual instances. Hypervisors are crucial to virtualization technology, enabling efficient utilization and management of computing resources.

84 | 85 |

What Are VMs

86 |

Virtual machines (VMs) are simulated computing environments that run on physical hardware. They enable multiple operating systems and applications to operate independently on a single physical server. Each VM functions as a separate computer, with its own operating system, resources (such as CPU, memory, and storage), and applications. VMs allow for efficient use of hardware resources, simplify system management, and provide increased flexibility in deployment and scalability.

87 | 88 |

What Are Containers

89 |

Containers are a form of virtualization that allows you to run applications in isolated environments. They package an application and its dependencies into a single unit that can run consistently across various computing environments. This ensures that the application will work the same way regardless of where it's deployed.

90 |

Containers leverage several key Linux features to provide isolation and resource management. Here are the main features:

91 |
    92 |
  • Namespaces: These provide process isolation by creating separate environments for containers. Each container gets its own namespace for different aspects: 93 |
      94 |
    • PID Namespace: Isolates process IDs, so processes in one container cannot see or interact with processes in another.
    • 95 |
    • Network Namespace: Provides each container with its own network stack, including IP addresses and network interfaces.
    • 96 |
    • Mount Namespace: Isolates the file system, so containers have their own views of the filesystem, independent of the host.
    • 97 |
    • UTS Namespace: Isolates hostname and domain name, allowing containers to have their own hostname.
    • 98 |
    • IPC Namespace: Isolates inter-process communication resources, ensuring containers cannot interfere with each other's IPC mechanisms.
    • 99 |
    • User Namespace: Isolates user and group IDs, enabling containers to have different user mappings from the host.
    • 100 |
    101 |
  • 102 |
  • Cgroups (Control Groups): These limit and isolate resource usage for containers, including CPU, memory, disk I/O, and network. This ensures that containers do not exceed their allocated resources and can help in balancing load and ensuring quality of service.
  • 103 |
  • Chroot: Changes the root directory for a process, isolating its file system from the rest of the system. This creates a sandbox environment, preventing the container from accessing files outside its designated directory tree.
  • 104 |
105 |

In summary, containers use Linux features to provide isolation, resource management, and a consistent runtime environment for applications. This enables efficient, secure, and portable application deployment across different environments.

106 |
107 | 108 |
109 |

VMs vs Containers

110 |

Both VMs and containers provide isolated environments for running applications, but they achieve this isolation in different ways.

111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 |
AspectVMsContainers
IsolationVMs provide hardware-level isolation by virtualizing the entire physical machine. Each VM runs its own operating system and applications.Containers provide process-level isolation by sharing the host OS kernel. They encapsulate the application and its dependencies, ensuring consistent runtime environments.
PerformanceVMs have higher overhead because they require running a separate OS for each VM. This can result in slower performance and increased resource usage.Containers have lower overhead as they share the host OS kernel. They are lightweight and start up faster, offering better performance and resource efficiency.
PortabilityVMs are less portable as they depend on the underlying hypervisor and hardware compatibility.Containers are highly portable because they include all necessary dependencies and can run on any system with a compatible container runtime.
Resource AllocationVMs allocate fixed amounts of resources (CPU, memory, storage) to each VM, which can lead to underutilization or overcommitment of resources.Containers can dynamically share resources, allowing for better resource utilization and scalability.
ManagementVMs require managing separate OS instances, which can be complex and resource-intensive.Containers simplify management by running on a shared OS kernel, reducing the need for managing multiple OS instances.
143 |
144 | 145 |
146 |

Docker vs LXC

147 |

Docker and LXC (Linux Containers) are both containerization technologies, but they have different focuses and use cases.

148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 |
AspectDockerLXC
FocusApplication-centric: Docker is designed to package and run individual applications and their dependencies in isolated containers.System-centric: LXC is designed to run full Linux systems in containers, making it suitable for running multiple processes and services.
User ExperienceDocker provides a higher-level, user-friendly interface and tooling for building, managing, and deploying containers.LXC provides a lower-level interface, giving users more control over container configuration and management.
Image ManagementDocker has a robust image management system with Docker Hub, allowing for easy distribution and versioning of container images.LXC does not have a centralized image repository, and image management is more manual and less standardized.
OrchestrationDocker has strong support for container orchestration tools like Docker Compose, Kubernetes, and Swarm.LXC has limited support for orchestration tools, making it less suitable for large-scale, complex deployments.
175 |
176 | 177 |
178 |

Docker

179 |

Docker is a platform for developing, shipping, and running applications inside containers. It provides an efficient way to package applications with their dependencies, ensuring consistency across different environments.

180 |
181 | 182 |
183 |

Docker Images

184 |

A Docker image is a lightweight, standalone, and executable software package that includes everything needed to run a piece of software, including the code, runtime, libraries, environment variables, and configuration files. Docker images are used to create containers, which are instances of the images that run the application.

185 |
186 |
# Example of a Dockerfile for a simple web application
187 | FROM node:14
188 | 
189 | # Set the working directory
190 | WORKDIR /app
191 | 
192 | # Copy application code
193 | COPY . .
194 | 
195 | # Install dependencies
196 | RUN npm install
197 | 
198 | # Expose the application port
199 | EXPOSE 3000
200 | 
201 | # Command to run the application
202 | CMD ["npm", "start"]
203 |                 
204 |
205 |
206 | 207 |
208 |

Docker Compose

209 |

Docker Compose is a tool for defining and running multi-container Docker applications. With Docker Compose, you can use a YAML file to configure your application's services, networks, and volumes. Then, with a single command, you can create and start all the services defined in the configuration.

210 |
211 |
212 | 213 |
214 |

Docker Volumes

215 |

Docker volumes are used to persist data generated by and used by Docker containers. They provide a way to store data outside of the container's writable layer, ensuring data is not lost when containers are stopped or removed.

216 |
217 |
# Example of creating a volume
218 | docker volume create my_volume
219 | 
220 | # Example of using a volume in a container
221 | docker run -d -v my_volume:/data my_image
222 |                 
223 |
224 |
225 |
226 |

Volume Types

227 |

Volumes are used to persist data generated by and used by Docker containers. There are different types of volumes:

228 |
    229 |
  • Bind Mounts: Bind mounts map a file or directory on the host machine to a file or directory in the container. They are directly dependent on the host machine's filesystem.
  • 230 |
  • Volumes: Docker volumes are managed by Docker and are stored in a part of the host filesystem that is managed by Docker (/var/lib/docker/volumes/). They are more flexible and can be used across multiple containers.
  • 231 |
  • tmpfs Mounts: tmpfs mounts store data in the host system's memory only, ensuring that the data is never written to the underlying storage. They are fast but ephemeral, as the data does not persist after the container stops.
  • 232 |
233 |
234 | 235 |
236 |

Docker Volume Drivers and Mount Options

237 |

Docker volumes can be managed using various volume drivers and mount options to customize how they are created, accessed, and managed.

238 | 239 |

Volume Drivers

240 |

Volume drivers allow Docker to integrate with various storage solutions. Some common volume drivers include:

241 |
    242 |
  • local: The default driver that stores volumes on the local filesystem.
  • 243 |
  • nfs: Network File System driver for sharing volumes over a network.
  • 244 |
  • flocker: A clustered container data volume manager.
  • 245 |
  • azurefile: Integrates with Azure File Storage.
  • 246 |
  • rexray/ebs: Integrates with Amazon Elastic Block Store (EBS).
  • 247 |
248 | 249 |

Mount Types

250 |

Docker supports different types of mounts:

251 |
    252 |
  • volume: A Docker-managed volume.
  • 253 |
  • bind: A bind mount that links a path on the host to a path in the container.
  • 254 |
  • tmpfs: A temporary filesystem mount that stores data in memory.
  • 255 |
256 | 257 |

Mount Options

258 |

When defining volumes, you can specify various options to control their behavior:

259 |
    260 |
  • readonly: Mount the volume as read-only.
  • 261 |
  • noexec: Prevent the execution of binaries on the mounted volume.
  • 262 |
  • nosuid: Ignore set-user-identifier or set-group-identifier bits.
  • 263 |
  • size: Specify the size of the tmpfs mount.
  • 264 |
265 |
266 | 267 |
268 |

Network Types

269 |

Docker provides several network types to manage how containers communicate with each other and with external systems:

270 |
    271 |
  • Bridge Network: The default network type for Docker containers. It allows containers to communicate with each other on the same host using a private internal network.
  • 272 |
  • Host Network: Shares the host's network namespace with the container, providing the container with direct access to the host's network interfaces.
  • 273 |
  • Overlay Network: Enables communication between containers running on different Docker hosts, typically used in multi-host orchestration setups like Docker Swarm or Kubernetes.
  • 274 |
  • Macvlan Network: Assigns a MAC address to each container, making it appear as a physical device on the network. Useful for integrating containers into an existing network infrastructure.
  • 275 |
  • None Network: Disables all networking for the container, providing a completely isolated environment.
  • 276 |
277 |
278 | 279 |
280 | 281 | 282 | 283 | -------------------------------------------------------------------------------- /srcs/requirements/bonus/static_web/tools/script.js: -------------------------------------------------------------------------------- 1 | // scripts.js 2 | 3 | document.addEventListener('DOMContentLoaded', function() { 4 | // Show/hide scroll-to-top button 5 | const scrollToTopButton = document.createElement('button'); 6 | scrollToTopButton.textContent = '↑'; 7 | scrollToTopButton.className = 'scroll-to-top'; 8 | document.body.appendChild(scrollToTopButton); 9 | 10 | window.addEventListener('scroll', function() { 11 | if (window.scrollY > 200) { 12 | scrollToTopButton.style.display = 'block'; 13 | } else { 14 | scrollToTopButton.style.display = 'none'; 15 | } 16 | }); 17 | 18 | scrollToTopButton.addEventListener('click', function() { 19 | window.scrollTo({ top: 0, behavior: 'smooth' }); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /srcs/requirements/bonus/static_web/tools/styles.css: -------------------------------------------------------------------------------- 1 | /* styles.css */ 2 | 3 | /* General styles */ 4 | body { 5 | font-family: Arial, sans-serif; 6 | line-height: 1.6; 7 | margin: 0; 8 | padding: 0; 9 | background-color: #f9f9f9; 10 | color: #333; 11 | } 12 | 13 | header { 14 | background: #2c3e50; 15 | color: #ecf0f1; 16 | padding: 20px 0; 17 | text-align: center; 18 | box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); 19 | } 20 | 21 | header h1 { 22 | margin: 0; 23 | font-size: 2.5rem; 24 | } 25 | 26 | header img { 27 | max-width: 100%; 28 | height: auto; 29 | } 30 | 31 | nav { 32 | background: #34495e; 33 | color: #ecf0f1; 34 | padding: 10px 0; 35 | text-align: center; 36 | box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); 37 | } 38 | 39 | nav ul { 40 | list-style: none; 41 | padding: 0; 42 | margin: 0; 43 | } 44 | 45 | nav ul li { 46 | display: inline; 47 | margin: 0 15px; 48 | } 49 | 50 | nav ul li a { 51 | color: #ecf0f1; 52 | text-decoration: none; 53 | font-size: 1.1rem; 54 | } 55 | 56 | nav ul li a:hover { 57 | text-decoration: underline; 58 | color: #3498db; 59 | } 60 | 61 | .container { 62 | width: 80%; 63 | margin: 20px auto; 64 | padding: 20px; 65 | background: #fff; 66 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); 67 | border-radius: 8px; 68 | } 69 | 70 | h2 { 71 | color: #3498db; 72 | border-bottom: 2px solid #3498db; 73 | padding-bottom: 10px; 74 | margin-bottom: 20px; 75 | } 76 | 77 | ul { 78 | margin: 0; 79 | padding: 0; 80 | list-style: disc; 81 | padding-left: 20px; 82 | } 83 | 84 | code { 85 | background: #f4f4f4; 86 | border: 1px solid #ddd; 87 | border-radius: 3px; 88 | padding: 5px; 89 | font-family: 'Courier New', Courier, monospace; 90 | } 91 | 92 | pre { 93 | background: #f4f4f4; 94 | border: 1px solid #ddd; 95 | border-radius: 3px; 96 | padding: 10px; 97 | overflow-x: auto; 98 | } 99 | 100 | table { 101 | width: 100%; 102 | border-collapse: collapse; 103 | margin-bottom: 20px; 104 | } 105 | 106 | table, th, td { 107 | border: 1px solid #ddd; 108 | } 109 | 110 | th, td { 111 | padding: 10px; 112 | text-align: left; 113 | } 114 | 115 | th { 116 | background: #3498db; 117 | color: #fff; 118 | } 119 | 120 | footer { 121 | background: #2c3e50; 122 | color: #ecf0f1; 123 | text-align: center; 124 | padding: 10px 0; 125 | position: fixed; 126 | bottom: 0; 127 | width: 100%; 128 | box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1); 129 | } 130 | 131 | .scroll-to-top { 132 | position: fixed; 133 | bottom: 20px; 134 | right: 20px; 135 | background: #3498db; 136 | color: #fff; 137 | border: none; 138 | border-radius: 50%; 139 | width: 50px; 140 | height: 50px; 141 | text-align: center; 142 | line-height: 50px; 143 | font-size: 24px; 144 | cursor: pointer; 145 | box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); 146 | display: none; 147 | } 148 | 149 | .scroll-to-top:hover { 150 | background: #2980b9; 151 | } 152 | -------------------------------------------------------------------------------- /srcs/requirements/mariadb/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | RUN apt-get update -y && apt-get install -y mariadb-server python3 4 | 5 | COPY ./tools/script.py / 6 | COPY ./conf/50-server.cnf /etc/mysql/mariadb.conf.d/ 7 | 8 | CMD ["python3", "script.py"] 9 | -------------------------------------------------------------------------------- /srcs/requirements/mariadb/conf/50-server.cnf: -------------------------------------------------------------------------------- 1 | # 2 | # These groups are read by MariaDB server. 3 | # Use it for options that only the server (but not clients) should see 4 | 5 | # this is read by the standalone daemon and embedded servers 6 | [server] 7 | 8 | # this is only for the mysqld standalone daemon 9 | [mysqld] 10 | 11 | # 12 | # * Basic Settings 13 | # 14 | 15 | user = mysql 16 | pid-file = /run/mysqld/mysqld.pid 17 | socket = /run/mysqld/mysqld.sock 18 | port = 3306 19 | basedir = /usr 20 | datadir = /var/lib/mysql 21 | tmpdir = /tmp 22 | lc-messages-dir = /usr/share/mysql 23 | lc-messages = en_US 24 | skip-external-locking 25 | 26 | # Broken reverse DNS slows down connections considerably and name resolve is 27 | # safe to skip if there are no "host by domain name" access grants 28 | #skip-name-resolve 29 | 30 | # Instead of skip-networking the default is now to listen only on 31 | # localhost which is more compatible and is not less secure. 32 | bind-address = 0.0.0.0 33 | 34 | # 35 | # * Fine Tuning 36 | # 37 | 38 | #key_buffer_size = 128M 39 | #max_allowed_packet = 1G 40 | #thread_stack = 192K 41 | #thread_cache_size = 8 42 | # This replaces the startup script and checks MyISAM tables if needed 43 | # the first time they are touched 44 | #myisam_recover_options = BACKUP 45 | #max_connections = 100 46 | #table_cache = 64 47 | 48 | # 49 | # * Logging and Replication 50 | # 51 | 52 | # Both location gets rotated by the cronjob. 53 | # Be aware that this log type is a performance killer. 54 | # Recommend only changing this at runtime for short testing periods if needed! 55 | #general_log_file = /var/log/mysql/mysql.log 56 | #general_log = 1 57 | 58 | # When running under systemd, error logging goes via stdout/stderr to journald 59 | # and when running legacy init error logging goes to syslog due to 60 | # /etc/mysql/conf.d/mariadb.conf.d/50-mysqld_safe.cnf 61 | # Enable this if you want to have error logging into a separate file 62 | #log_error = /var/log/mysql/error.log 63 | # Enable the slow query log to see queries with especially long duration 64 | #slow_query_log_file = /var/log/mysql/mariadb-slow.log 65 | #long_query_time = 10 66 | #log_slow_verbosity = query_plan,explain 67 | #log-queries-not-using-indexes 68 | #min_examined_row_limit = 1000 69 | 70 | # The following can be used as easy to replay backup logs or for replication. 71 | # note: if you are setting up a replication slave, see README.Debian about 72 | # other settings you may need to change. 73 | #server-id = 1 74 | #log_bin = /var/log/mysql/mysql-bin.log 75 | expire_logs_days = 10 76 | #max_binlog_size = 100M 77 | 78 | # 79 | # * SSL/TLS 80 | # 81 | 82 | # For documentation, please read 83 | # https://mariadb.com/kb/en/securing-connections-for-client-and-server/ 84 | #ssl-ca = /etc/mysql/cacert.pem 85 | #ssl-cert = /etc/mysql/server-cert.pem 86 | #ssl-key = /etc/mysql/server-key.pem 87 | #require-secure-transport = on 88 | 89 | # 90 | # * Character sets 91 | # 92 | 93 | # MySQL/MariaDB default is Latin1, but in Debian we rather default to the full 94 | # utf8 4-byte character set. See also client.cnf 95 | character-set-server = utf8mb4 96 | collation-server = utf8mb4_general_ci 97 | 98 | # 99 | # * InnoDB 100 | # 101 | 102 | # InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/. 103 | # Read the manual for more InnoDB related options. There are many! 104 | # Most important is to give InnoDB 80 % of the system RAM for buffer use: 105 | # https://mariadb.com/kb/en/innodb-system-variables/#innodb_buffer_pool_size 106 | #innodb_buffer_pool_size = 8G 107 | 108 | # this is only for embedded server 109 | [embedded] 110 | 111 | # This group is only read by MariaDB servers, not by MySQL. 112 | # If you use the same .cnf file for MySQL and MariaDB, 113 | # you can put MariaDB-only options here 114 | [mariadb] 115 | 116 | # This group is only read by MariaDB-10.5 servers. 117 | # If you use the same .cnf file for MariaDB of different versions, 118 | # use this group for options that older servers don't understand 119 | [mariadb-10.5] -------------------------------------------------------------------------------- /srcs/requirements/mariadb/tools/script.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | from os import system 4 | import subprocess 5 | import shutil 6 | import time 7 | 8 | subprocess.run(["service", "mariadb", "start"]) 9 | time.sleep(5) 10 | 11 | # # Secure the installation 12 | 13 | user = f""" 14 | mysql_secure_installation << EOF > /dev/null 2>&1 15 | n 16 | {os.environ.get('MYSQL_PASSWORD')} 17 | {os.environ.get('MYSQL_PASSWORD')} 18 | y 19 | n 20 | n 21 | n 22 | n 23 | EOF 24 | """ 25 | subprocess.run(user, shell=True, check=False) 26 | 27 | create_db_cmd = f"CREATE DATABASE IF NOT EXISTS {os.environ.get('MYSQL_DATABASE_NAME')};" 28 | create_user_cmd = f"CREATE USER IF NOT EXISTS '{os.environ.get('MYSQL_USER')}'@'%' IDENTIFIED BY '{os.environ.get('MYSQL_PASSWORD')}';" 29 | grant_privileges_cmd = f"GRANT ALL PRIVILEGES ON {os.environ.get('MYSQL_DATABASE_NAME')}.* TO '{os.environ.get('MYSQL_USER')}'@'%';" 30 | #reload table and update the user privileges in memory 31 | flush_privileges_cmd = "FLUSH PRIVILEGES;" 32 | 33 | for cmd in [create_db_cmd, create_user_cmd, grant_privileges_cmd, flush_privileges_cmd]: 34 | subprocess.run(["mysql", "-u", "root", "-p" + os.environ.get('MYSQL_PASSWORD'), "-e", cmd]) 35 | 36 | subprocess.run(["mysqladmin", "shutdown", "-u", "root", "-p" + os.environ.get('MYSQL_PASSWORD')]) 37 | subprocess.run(["mariadbd"]) -------------------------------------------------------------------------------- /srcs/requirements/nginx/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | RUN apt-get -y update && apt-get -y upgrade && apt-get install -y nginx openssl 4 | 5 | COPY conf/nginx.conf /etc/nginx/sites-enabled/default 6 | 7 | RUN mkdir /etc/nginx/certs 8 | RUN openssl req -newkey rsa:4096 -sha256 -x509 -days 100 -nodes -out /etc/nginx/certs/ssl.crt -keyout /etc/nginx/certs/ssl.key -subj "/C=ma/L=Khouribga/O=42/OU=1337kh/CN=ouaarabe/" 9 | 10 | ENTRYPOINT ["nginx", "-g" ,"daemon off;"] 11 | 12 | -------------------------------------------------------------------------------- /srcs/requirements/nginx/conf/nginx.conf: -------------------------------------------------------------------------------- 1 | server { 2 | 3 | listen 443 ssl; 4 | 5 | 6 | # sets the root directory for the server. All files will be served from this dir 7 | root /var/www/html/; 8 | server_name ouaarabe.42.fr; 9 | index index.php index.html index.htm; 10 | 11 | ssl_protocols TLSv1.3 TLSv1.2; 12 | ssl_certificate /etc/nginx/certs/ssl.crt; 13 | ssl_certificate_key /etc/nginx/certs/ssl.key; 14 | 15 | location /adminer { 16 | proxy_pass http://adminer:8081; 17 | } 18 | 19 | 20 | # use the try_files directive to try to serve the requested URI as a file or directory 21 | location / { 22 | try_files $uri $uri/ =404; 23 | } 24 | 25 | #handle requests for PHP files 26 | location ~ \.php$ { 27 | fastcgi_split_path_info ^(.+\.php)(/.+)$; 28 | fastcgi_pass wordpress:9000; 29 | include fastcgi_params; 30 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 31 | fastcgi_param PATH_INFO $fastcgi_path_info; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /srcs/requirements/wordpress/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | 3 | RUN apt-get -y update && apt-get -y upgrade && apt-get install -y python3 php php-fpm \ 4 | php-cgi php-cli php-mysql wget php-redis 5 | 6 | WORKDIR /var/www/html 7 | 8 | RUN wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar 9 | 10 | RUN chmod +x wp-cli.phar 11 | 12 | RUN mv wp-cli.phar /usr/local/bin/wp 13 | RUN wp core download --path=/var/www/html --allow-root 14 | 15 | COPY ./tools/script.py / 16 | COPY ./conf/wp-config.php /var/www/html/wp-config.php 17 | 18 | WORKDIR / 19 | 20 | ENTRYPOINT [ "python3", "script.py"] 21 | 22 | 23 | #/etc/php- fpm. conf. -------------------------------------------------------------------------------- /srcs/requirements/wordpress/conf/wp-config.php: -------------------------------------------------------------------------------- 1 |