0% encontró este documento útil (0 votos)
1 vistas35 páginas

Docker 29)

El documento es una guía rápida de aprendizaje sobre Docker, que cubre desde la instalación y configuración hasta conceptos avanzados como Dockerfiles y orquestación. Se destacan las diferencias entre máquinas virtuales y contenedores, así como las ventajas de usar Docker para la portabilidad y eficiencia de recursos. Además, se incluyen instrucciones para trabajar con imágenes, contenedores, redes y volúmenes, así como mejores prácticas de seguridad y optimización del rendimiento.

Cargado por

Juan M.
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
1 vistas35 páginas

Docker 29)

El documento es una guía rápida de aprendizaje sobre Docker, que cubre desde la instalación y configuración hasta conceptos avanzados como Dockerfiles y orquestación. Se destacan las diferencias entre máquinas virtuales y contenedores, así como las ventajas de usar Docker para la portabilidad y eficiencia de recursos. Además, se incluyen instrucciones para trabajar con imágenes, contenedores, redes y volúmenes, así como mejores prácticas de seguridad y optimización del rendimiento.

Cargado por

Juan M.
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF o lee en línea desde Scribd
Docker Quick Learning Guide CORE Sama A so aA a a Oe UNL sity ce es Pea a IMAGES Cre Cog eee ea ite SME iy emir) ORCHESTRATION Se Cee ey ee EN Ly enc eae _ okey Fd 7) fe pe.) eg Crys 7 BETTER ya me tae eT eT RS isk ae AUTOMATION From Beginner to Pro - Learn Docker the Smart Way Want Linux & DevOps Materials? <> Message to Me for Price Details. Docker Quick Learning Guide | Table of Contents . Introduction to Docker © 1.1 What is Docker? © 1.2 Why Docker Matters ° 1.3 Virtual Machines vs Containers © 1.4 Core Docker Concepts nN Setting Up Docker © 2.1 System Requirements © 2.2 Installing Docker Desktop (Windows/Mac) © 2.3 Installing Docker Engine (Linux) © 2.4 Verifying Your Installation ° 2.5 Docker Dashboard Overview wo Your First Docker Commands © 3.1 Understanding the Docker CLI © 3.2 Running Your First Container © 3.3 Listing Containers © 3.4 Stopping and Removing Containers 4. Working with Docker Images © 4.1 What are Docker Images? © 4.2 Pulling Images from Docker Hub © 4.3 Listing Local Images ° 4.4 Removing Images © 4.5 Understanding Image Tags 5. Container Lifecycle Management © 5.1 Running Containers in Detached Mode © 5.2 Attaching to Running Containers © 5.3 Pausing and Unpausing Containers Want Linux & DevOps Materials? <> Message to Me for Price Details. o 5.4 Restarting Containers o 5.5 Container Logs . Port Mapping and Networking a © 6.1 What is Port Mapping? © 6.2 Publishing Ports ° 6.3 Docker Networks Overview © 6.4 Creating Custom Networks © 6.5 Connecting Containers to Networks 7. Working with Volumes © 7.1 Why Persistence Matters © 7.2 Types of Volumes © 7.3 Creating and Managing Volumes © 7.4 Mounting Volumes to Containers © 7.5 Bind Mounts for Development oo Environment Variables © 8.1 What are Environment Variables? © 8.2 Setting Environment Variables © 8.3 Using .env Files © 8.4 Variable Precedence 9. Introduction to Dockerfiles © 9.1 What is a Dockerfile? © 9.2 Dockerfile Syntax © 9.3 Creating Your First Dockerfile © 9.4 Building Images with Dockerfile © 9.5 Layered Architecture 10, Dockerfile Instructions Guide © 10.1 FROM - Base Images © 10.2 WORKDIR - Working Directory © 10.3 COPY and ADD - Adding Files © 10.4 RUN - Executing Commands © 10.5 CMD and ENTRYPOINT Want Linux & DevOps Materials? <> Message to Me for Price Details. © 10.6 EXPOSE - Port Documentation © 10.7 ENV - Environment Variables © 10.8 USER - Running as Non-Root 11. Multi-Container Applications © 11.1 The Challenge of Multiple Services © 11.2 Introduction to Docker Compose © 11.3 Installing Docker Compose © 11.4 Creating a [Link] File © 11.5 Starting Multiple Containers 12. Docker Compose Advanced © 12.1 Service Dependencies © 12.2 Environment Variables in Compose © 12.3 Volumes in Compose ° 12.4 Networks in Compose ° 12.5 Compose Commands 13. Real-World Example: Web Application © 13.1 Project Structure © 13.2 Creating the Frontend Service © 13.3 Creating the Backend Service © 13.4 Adding a Database © 13.5 Bringing It All Together 14. Managing Data o 14.1 Database Persistence © 14.2 Backup Strategies © 14.3 Restoring Data ° 14.4 Data Migration 15. Docker Registries © 15.1 What is a Registry? © 15.2 Docker Hub © 15.3 Tagging Images for Upload © 15.4 Pushing Images to Docker Hub Want Linux & DevOps Materials? <> Message to Me for Price Details. o 15.5 Private Registries 16. Debugging and Troubleshooting © 16.1 Common Errors © 16.2 Inspecting Containers © 16.3 Executing Commands Inside Containers © 16.4 Viewing Logs Effectively © 16.5 Resource Usage Monitoring 17. Security Best Practices © 17.1 Running Containers as Non-Root © 17.2 Scanning Images for Vulnerabilities © 17.3 Securing Docker Daemon © 17.4 Secret Management © 17.5 Network Security 18. Performance Optimization © 18.1 Image Size Optimization © 18.2 Caching Strategies © 18.3 Multi-Stage Builds © 18.4 Resource Limits © 18.5 Cleanup Commands 19. Testing with Docker © 19.1 Isolated Test Environments © 19,2 Running Tests in Containers © 19.3 Integration Testing © 19.4 Continuous Integration Setup 20. Development Workflow © 20.1 Local Development Setup © 20.2 Hot Reloading © 20.3 Debugging Applications © 20.4 Version Control with Docker 2 Production Deployment Want Linux & DevOps Materials? <> Message to Me for Price Details. © 21.1 Building Production Images o 21.2 Deployment Strategies ° 21.3 Health Checks ° 21.4 Restart Policies © 21.5 Logging in Production 22. Orchestration Introduction © 22.1 Why Orchestration? © 22.2 Kubernetes Overview © 22.3 Docker Swarm ° 22.4When to Use Each 23. Useful Docker Tools © 23.1 Docker Desktop Extensions © 23.2 Portainer ° 23.3 VS Code Docker Extension ° 23.4 Docker Scout © 23.5 Watchtower 24. Common Patterns and Anti-patterns © 24.1 Best Practices © 24.2 Things to Avoid © 24.3 Optimization Patterns © 24.4 Security Anti-patterns 25. Next Steps © 25.1 Learning Resources © 25.2 Certification Paths © 25.3 Community and Support © 25.4 Practicing with Real Projects | 1.1 What is Docker? Docker is an open-source platform that automates the deployment, scaling, and management of applications. It uses containerization technology to Want Linux & DevOps Materials? <> Message to Me for Price Details. package software into standardized units called containers. These containers include everything an application needs to run: code, runtime, system tools, libraries, and settings. Imagine you want to run a Python application on your computer. You need to install Python, set up the correct version, install dependencies, configure environment variables, and ensure everything works. Now imagine you want to share this application with a colleague or deploy it to a server. You would need to repeat all these steps on every machine. Docker solves this problem by packaging your application and its dependencies into a container that runs consistently across any system. Key concept: Docker containers run on any Linux-based system and share the host kernel, making them lightweight and fast. They provide process-level isolation, meaning each container runs as an isolated process on the host system. | 1.2 Why Docker Matters Docker revolutionized software development by solving the "works on my machine" problem. Here are the primary benefits: Consistency Across Environments: When you run your application in a Docker container, it behaves the same whether it's on your laptop, your colleague's computer, or a production server. The container includes everything needed, eliminating environment-specific issues. Resource Efficiency: Unlike virtual machines (VMs) that require a complete operating system, Docker containers share the host OS kernel. This makes them much lighter, starting in milliseconds and using significantly less memory. Isolation: Each Docker container runs in its own isolated environment with its own filesystem, network stack, and process space. This prevents applications from interfering with each other and provides security boundaries. Portability: Docker containers can run anywhere Docker is installed. You can build a container on your Windows laptop and deploy it on a Linux server without any modifications. Version Control: Docker images are versioned, allowing you to track changes, roll back to previous versions, and maintain multiple application versions simultaneously. | 1.3 Virtual Machines vs Containers Want Linux & DevOps Materials? <> Message to Me for Price Details. To understand Docker fully, it's essential to distinguish between virtual machines and containers. Virtual Machines (VMs) are heavy, full-blown operating systems running on top of a hypervisor. Each VM includes: + Acomplete guest operating system « Virtual hardware (CPU, memory, storage, network) * The application and its dependencies « Independent kernel and system libraries This approach provides strong isolation but requires significant resources. A typical VM can take several gigabytes of storage and minutes to start. Containers, on the other hand: * Share the host OS kernel * Include only the application and its dependencies + Do not require a separate operating system * Start in milliseconds + Use megabytes of storage Think of containers as lightweight, isolated process spaces that run on the host system. They use Linux kernel features like namespaces and cgroups to provide isolation. A VM is like moving to a new house (complete with all furniture), while a container is like renting a room in an existing house. | 1.4 Core Docker Concepts Before diving into hands-on work, understand these fundamental Docker concepts: Image: A Docker image is a read-only template containing instructions for creating a container. You can think of it as a snapshot of a configured system. Images are composed of layers, each representing a change to the filesystem. You can create your own images or use pre-built images from Docker Hub. Container: A container is a running instance of an image. When you start a container, Docker adds a writable layer on top of the image. This writable layer allows the container to make changes without affecting the original image. Multiple containers can run from the same image. Registry: A registry is a repository for Docker images. Docker Hub is the default public registry where you can find thousands of pre-built images. You Want Linux & DevOps Materials? <> Message to Me for Price Details. can also set up private registries for your organization. Dockerfile: A Dockerfile is a text file containing instructions for building a Docker image. It specifies the base image, commands to run, files to copy, and how to configure the environment. Docker Daemon: The Docker daemon (dockerd) is the background service that manages Docker objects. It listens for API requests and handles container lifecycle, image management, and network configuration. Docker Client: The Docker client (docker CLI) is the command-line interface you use to interact with the Docker daemon. When yourun docker run, you're sending commands to the daemon through this client. Docker Compose: A tool for defining and running multi-container Docker applications. You use a YAML file to configure application services, networks, and volumes, then start everything with a single command | 2.1 System Requirements Docker requires a 64-bit operating system. For Windows, you need Windows 10 version 1903 or later (Pro, Enterprise, or Education editions) or Windows 11. For Mac, you need macOS version 10.15 or later. Linux distributions need kernel version 3.10 or later and support for cgroups and namespaces. Before installing, ensure your system meets these requirements. On Linux, you can check your kernel version with: uname -r This command displays your kernel version. If the output shows 3.10 or higher, you're ready to proceed. On Windows, enable hardware virtualization in your BIOS settings and ensure Windows Hyper-V or WSL 2 is enabled. On Mac, make sure hardware virtualization (VT-x) is supported (most modern Macs have this enabled by default). | 2.2 Installing Docker Desktop (Windows/Mac) Docker Desktop provides a GUI interface for managing Docker. Here's how to install it 1. Navigate to the Docker official website and locate the download section. Want Linux & DevOps Materials? <> Message to Me for Price Details. 2. Click the Download for Windows or Download for Mac button. 3. Wait for the installer file to download completely. 4. Locate the downloaded installer file and double-click it. 5. Run the installer if prompted by your operating system. 6. Check the option to install additional components if offered. 7. Accept the license agreement by clicking Accept. 8. Click Install to begin the installation process. 9. Wait for the installation to complete (this may take several minutes) 10. Click Finish and Restart your computer if prompted. 11. After restart, launch Docker Desktop from your applications. 12. Accept the service agreement and subscription terms. 13. Docker Desktop will start the Docker engine and show its whale icon in the system tray. For Windows users specifically, you may need to enable WSL 2 during installation. When prompted, select the option to use WSL 2 based engine. This provides better performance and compatibility. | 2.3 Installing Docker Engine (Linux) Linux users install the Docker Engine directly without a GUI. The process varies slightly by distribution. Ubuntu/Debian installation: 1. Update your package index: sudo apt update 2. Install prerequisite packages: sudo apt install apt-transport-https ca-certificates curl sof tware-properties-common 3. Add Docker's official GPG key: Want Linux & DevOps Materials? <> Message to Me for Price Details. curl -fsSL [Link] | sud © gpg --dearmor -o /usr/share/keyrings/docker-archive-keyrin g-9p9 4. Add the stable repository: echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-ar [Link]] [Link] .com/1inux/ubuntu §(1sb_release -cs) stable” | sudo tee /etc/apt/sources. list. d/[Link] > /dev/null 5, Update again with the new repository: sudo apt update 6. Install Docker Engine sudo apt install docker-ce docker-ce-cli [Link] 7. Verify Docker is running sudo systemctl status docker 8. Add your user to the docker group to run without sudo: sudo usermod -aG docker SUSER 9, Log out and back in for group changes to take effect. | 2.4 Verifying Your Installation After installation, verify that Docker is working correctly. Open a terminal or command prompt and run: docker --version This displays the Docker version information. You should see output similar to “Docker version 20.10.24, build 297e128". Next, test Docker's functionality by running a simple container: docker run hello-world This command downloads a test image and runs a container. If successful, you'll see a welcome message explaining that Docker is installed and working Want Linux & DevOps Materials? <> Message to Me for Price Details. properly. For Docker Desktop users, open the application to see the dashboard. It should show “Engine running" and provide access to the GUI interface where you can manage containers, images, and volumes. | 2.5 Docker Dashboard Overview Docker Desktop's dashboard provides a visual interface for managing Docker. Here's what you'll find: The left sidebar contains navigation to different sections. Containers shows all running and stopped containers, letting you start, stop, or remove them with a single click. Images displays your downloaded and built images. Volumes shows persistent data storage. Networks displays container networking. The main view changes based on the selected section. For containers, you see a list with each container's name, status, and resource usage. Clicking a container reveals detailed information including logs, inspect data, and stats. The settings gear lets you configure Docker Desktop. Here you can adjust resource limits (CPU, memory), change network settings, and enable experimental features. The CLI console at the bottom provides quick access to terminal commands directly from the dashboard. | 3.1 Understanding the Docker CLI The Docker CLI (Command Line Interface) is the primary tool for interacting with Docker. Commands follow a specific pattern: docker [command] [options] [arguments] The command specifies what action to perform, suchas run, ps,or pull. Options modify the command's behavior, like -d for detached mode. Arguments provide specific details like container names or image tags. Common Docker commands you'll use frequently: docker run: Creates and starts a new container from an image docker ps: Lists running containers docker stop: Gracefully stops a running container Want Linux & DevOps Materials? <> Message to Me for Price Details. docker rm: Removes a stopped container docker images: Lists downloaded images docker pull: Downloads an image from a registry docker exec: Runs commands inside a running container The CLI provides detailed help for each command. You can explore help by typing docker --help Or get help for a specific command: docker run --help | 3.2 Running Your First Container Now you'll run your first real container. Start with a simple NGINX web server: docker run nginx When you run this command, Docker: 1. Checks for the ‘nginx’ image locally 2. If not found, downloads it from Docker Hub 3. Creates a container from the image 4. Starts the container and runs the default command You'll see the NGINX server output in your terminal. It will keep running until you stop it. The terminal appears blocked because the container is running in the foreground. To stop it, press Ctrl+C. Now run a container with a different approach: docker run -d --name my-nginx nginx This command uses several options: « -d runs the container in detached mode (in the background) « --name my-nginx assigns a custom name to the container The container starts and runs in the background, returning control to your terminal. You'll see a container ID printed, which you can use to reference the container. | 3.3 Listing Containers Want Linux & DevOps Materials? <> Message to Me for Price Details. To see which containers are running, use’ docker ps This shows: Container ID (a unique identifier) Image name Command being executed Creation time Status (running, exited, etc.) Ports Container name To see all containers including stopped ones, add the -a flag: docker ps -a This displays every container you've created, including those that have exited or been stopped. You'll see that the hello-world container from the verification step is now in an "exited" state. For more detailed information, you can format the output: docker ps --format “table {{.Names}}\t{{.Status}}\t{{.Imag e}y" This creates a custom view showing only name, status, and image. | 3.4 Stopping and Removing Containers To stop a running container: docker stop my-nginx This sends a SIGTERM signal to the container, allowing it to shut down gracefully, It may take a few seconds for the container to stop completely. If a container won't stop gracefully, you can force it: docker kill my-nginx This sends a SIGKILL signal, immediately terminating the container. Want Linux & DevOps Materials? <> Message to Me for Price Details. After stopping, containers remain on your system and can be restarted. To remove a container completely: docker rm my-nginx You cannot remove a running container. Stop it first, or use: docker rm -f my-nginx The -f flag forces removal even if the container is running. To remove all stopped containers at once: docker container prune This asks for confirmation before removing all containers in the exited state. | 4.1 What are Docker Images? A Docker image is a lightweight, standalone, executable package that includes everything needed to run software: code, runtime, system tools, libraries, and settings. Images are created from instructions in a Dockerfile and consist of multiple layers. Think of an image as a snapshot of a file system at a specific point in time. When you run a container from an image, you get an instance of that snapshot with a writable layer on top. Images are stored as layers to save space and improve performance. For example, if you have multiple images that all start with the same Ubuntu base, they share the Ubuntu layer, saving disk space and speeding up downloads. The docker images command shows you what's stored locally: docker images This lists all images with their repository name, tag, image ID, creation date, and size. | 4.2 Pulling Images from Docker Hub Docker Hub is the default public registry containing thousands of images. You can browse available images at [Link]. Want Linux & DevOps Materials? <> Message to Me for Price Details. To download an image without running it: docker pull node:18 This downloads the [Link] 18 image from Docker Hub. The :18 specifies the tag (version). If you dor't specify a tag, Docker pulls the latest tag by default. Common images you might pull: © python:3.11 - Python 3.11 * mysql:8 - MySQL 8 * postgres: 15 - PostgreSQL 15 * redis:7 -Redis 7 * nginx:latest - Latest NGINX * ubuntu:22.04 - Ubuntu 22.04 LTS You can search for images directly from the CLI: docker search nginx This shows available NGINX images with star ratings and official status. | 4.3 Listing Local Images View all images you have downloaded or created: docker images The output shows: « REPOSITORY: The name of the image * TAG: The version or variant + IMAGE ID: Unique identifier (first 12 characters shown) « CREATED: When the image was created « SIZE: Storage space used For more detailed information, you can inspect an image: docker inspect nginx This returns a JSON object containing all configuration details including environment variables, exposed ports, and volumes. Want Linux & DevOps Materials? <> Message to Me for Price Details. To see only image IDs (useful for scripts): docker images -q | 4.4 Removing Images When you no longer need an image, remove it to free up space: docker rmi nginx This removes the image with the repository name. You can also use the image ID docker rmi abe123def456 If an image is being used by a container, Docker prevents removal. Force removal: docker rmi -f nginx Remove all unused images: docker image prune This removes images that aren't referenced by any container. You can add - a to remove all unused images, including those with no tags: docker image prune -a | 4.5 Understanding Image Tags Tags are labels for images, typically representing versions. A full image reference looks like: [registry/]repository[ :tag] The registry defaults to Docker Hub, repository is the image name, and tag is the version. Examples: * nginx:latest - Most recent stable version * nginx:1.25 - Specific version * python:3.11-slim - Slim variant (smaller size) * ubuntu:28.64 - Specific Ubuntu version Want Linux & DevOps Materials? <> Message to Me for Price Details. * myregistry/myapp:dev - Custom registry and tag Tags are not unique; multiple tags can point to the same image. For example, ubuntu:2@.04 and ubuntu:focal both refer to the same Ubuntu release. You can tag your own images: docker tag my-app:latest myregistry/my-app:1.8. This creates a new tag for an existing image. When pulling images, you can specify multiple tags: docker pull alpine:3.18 docker pull alpine:latest | 5.1 Running Containers in Detached Mode Detached mode runs containers in the background, returning control to the terminal. This is the most common way to run services. docker run -d nginx The -d flag stands for “detach”. Docker returns the container ID immediately while the container runs in the background. You can combine detached mode with port mapping: docker run -d -p 8886:80 nginx This maps port 8080 on your host to port 80 inside the container. You can now access NGINX by navigating to http: //localhost:880 in your browser. To attach to a running container's output: docker attach container_name This connects your terminal to the container's standard input, output, and error. Press Ctrl+P then Ctrl+Q to detach without stopping. | 5.2 Attaching to Running Containers Want Linux & DevOps Materials? <> Message to Me for Price Details. Sometimes you need to interact with a running container. The attach command connects your terminal to a container's main process: docker attach my-nginx After attaching, any output from the container appears in your terminal. To detach safely, use Ctrl+P followed by Ctrl+Q (this is the Docker escape sequence). If you want to see container output without attaching: docker logs my-nginx This shows the container's output from the beginning. Add -f to follow the output: docker logs -f my-nginx | 5.3 Pausing and Unpausing Containers You can temporarily freeze a container without stopping it: docker pause my-nginx This suspends all processes in the container. The container remains in memory but doesn't execute any operations. To resume: docker unpause my-nginx The container continues exactly where it left off. This is different from stopping, which terminates processes and would require restarting. | 5.4 Restarting Containers Containers can be restarted in several ways: docker restart my-nginx This stops and starts the container. It's useful when you've changed configuration or need to recover from errors. To start a stopped container: docker start my-nginx Want Linux & DevOps Materials? <> Message to Me for Price Details. Unlike run which creates anew container, start uses an existing container. Automatic restart policies ensure containers recover from crashes: docker run -d --restart always nginx Available policies: no: Never restart (default) always: Always restart on-failure: Restart only if exit code is non-zero unless-stopped: Similar to always but doesn't restart if manually stopped | 5.5 Container Logs Logs are essential for troubleshooting. View container logs: docker logs my-nginx Options for log viewing: * -f or --follow : Stream new logs * --tail 59: Show last 50 lines * --since 1h: Showlogs from the last hour . timestamps : Add timestamps to each line Example showing the last 100 lines with timestamps: docker logs --tail 180 --timestamps my-nginx You can also inspect log configuration: docker inspect my-nginx | grep LogConfig | 6.1 What is Port Mapping? Docker containers run in an isolated network environment. They can't be accessed from outside without explicit configuration. Port mapping creates a bridge between host ports and container ports. Want Linux & DevOps Materials? <> Message to Me for Price Details. Containers expose ports internally. For example, NGINX listens on port 80 inside the container. To access it from your browser, you need to map a host port to the container port. The format is: -p host_port :container_port Or more explicitly: -p host_ip:host_port:container_port | 6.2 Publishing Ports Publish ports when running a container: docker run -d -p 8080:8@ nginx You can publish multiple ports: docker run -d -p 8@80:80 -p 443:443 nginx Publish to a specific IP: docker run -d -p 127.0.@.1:8088:88 nginx This only allows access from localhost. To publish all available ports to random host ports: docker run -d -P nginx The -P flag tells Docker to map all exposed ports to random high-number ports on the host. Use docker port to see the mappings: docker port my-nginx | 6.3 Docker Networks Overview Docker networks provide isolation and allow containers to communicate. Docker creates several default networks: Bridge (default): The default network for containers. Each container on a bridge network can communicate with others on the same network. Host: Removes network isolation, using the host's network stack directly. The container shares the host's IP and ports. 20 Want Linux & DevOps Materials? <> Message to Me for Price Details. None: Disables networking, providing only a loopback interface. Overlay: Multi-host networking for Docker Swarm. When you run a container without specifying a network, it's connected to the default bridge network. Containers on the bridge can communicate, but require port mapping for external access. | 6.4 Creating Custom Networks Custom networks provide better isolation and service discovery: docker network create my-network List all networks: docker network ls Inspect a network: docker network inspect my-network Remove a network: docker network rm my-network Custom networks have DNS resolution, allowing containers to communicate using container names. This means if you have a container named web on the same custom network, you can connect to it from another container using web:8@. | 6.5 Connecting Containers to Networks Connect containers to networks at runtime: docker run -d --name web --network my-network nginx docker run -d --name api --network my-network node:18 Add a running container to a network: docker network connect my-network web Disconnect a container: docker network disconnect my-network web 21 Want Linux & DevOps Materials? <> Message to Me for Price Details. Containers on the same custom network can communicate freely using container names: docker exec api ping web This demonstrates that DNS resolution works within the custom network. | 7.1 Why Persistence Matters By default, containers are stateless. When a container is removed, all data it created is lost. This is a problem for applications that need to store data permanently, like databases. Volumes provide persistent storage for containers. They allow you to: + Store data that survives container deletion * Share data between containers « Manage data independently from container lifecycle There are three main ways to manage data in Docker: « Volumes: Managed by Docker, stored in a specific directory « Bind mounts: Mount a host directory into the container + tmpfs mounts: Store data in memory, not persistent | 7.2 Types of Volumes Docker Volumes: Created and managed by Docker. They're completely independent of containers and can be used across multiple containers. Docker stores them in a specific location ( /var/lib/docker/volumes/ ). Bind Mounts: Directly mount a host directory into the container. Any changes in the container reflect on the host and vice versa. This is excellent for development because you can edit code on the host and see changes instantly. tmpfs Mounts: Temporary storage in memory. Data disappears when the container stops. This is useful for sensitive data or caching. | 1.3 Creating and Managing Volumes Create a volume: 22 Want Linux & DevOps Materials? <> Message to Me for Price Details. docker volume create my-data List all volumes: docker volume 1s Inspect a volume: docker volume inspect my-data Remove a volume: docker volume rm my-data Remove all unused volumes: docker volume prune Volumes exist independently of containers. You can create them before running containers, or Docker can create them automatically when needed. | 7.4 Mounting Volumes to Containers Mount a volume when running a container: docker run -d --name db -v my-data:/var/lib/mysql mysql:8 The -y my-data:/var/lib/mysgql mounts the volume my-data to /var/lib/mysql inside the container. Using the newer --mount syntax (more explicit): docker run -d --name db --mount type=volume, source=my-data, ta rget=/var/lib/mysql mysql:8 Mount multiple volumes: docker run -d --name app -v volumel:/data -v volume2: /config my-app | 7.5 Bind Mounts for Development Bind mounts connect a host directory to a container, allowing real-time file sharing: docker run -d --name dev -v /path/on/host:/app my-dev-image 23 Want Linux & DevOps Materials? <> Message to Me for Price Details. For example, mounting your current directory: docker run -d --name dev -v $(pwd):/app node:18 This mounts the current directory to /app inthe container. Any changes made to files in the current directory appear in the container and vice versa Combine bind mounts with nodemon or similar tools for development: docker run -d --name dev -v $(pwd):/app -w /app node:18 npm r un dev This runs a development server with live reloading. Be careful with bind mounts in production because they expose host filesystem structure and can cause security issues. | 8.1 What are Environment Variables? Environment variables are key-value pairs that configure application behavior. They're commonly used for: « Database connection strings + API keys + Feature flags * Application mode (development/production) * Port configurations Docker passes environment variables to containers, allowing runtime configuration without changing code. | 8.2 Setting Environment Variables Use the -e flag when running containers: docker run -d -e DB_HOST=localhost -e DB_PORT=5432 my-app Set multiple variables: docker run -d -e DB_HOST=localhost -e DB_PORT=5432 -e DEBUG=t rue my-app Inspect environment variables in a container: 24 Want Linux & DevOps Materials? <> Message to Me for Price Details. docker exec my-container env Or inspect a specific container: docker inspect my-container | grep -A 5 Env | 8.3 Using .env Files Store environment variables in a .eny file for convenience: Create a filenamed .eny with content: DB_HOST=localhost DB_PORT=5432 DB_USER=admin DB_PASSWORD=secret DEBUG=false Use this file when running containers: docker run -d --env-file .env my-app Docker reads the file and sets each variable in the container. In Docker Compose, you can reference the environment file: services: app: env_file: - env | 8.4 Variable Precedence Docker follows a specific order when determining environment variable values: 1. Highest priority: Variables set with -e on the command line 2. Variables in Dockerfile using the ENV instruction 3. Variables from. eny files 4, Lowest priority: Variables from Docker Compose environment section This priority system allows overriding values for different environments. For security, never store secrets in environment variables. Use Docker secrets or external secret management tools for production. 25 Want Linux & DevOps Materials? <> Message to Me for Price Details. | 9.1 What is a Dockerfile? A Dockerfile is a text file containing instructions for building a Docker image. It's the recipe for creating reproducible, shareable application images. Each instruction in a Dockerfile creates a layer in the image. Layers are cached, making builds faster. When you change an instruction, Docker rebuilds only the layers that changed and later layers Dockerfiles are essential for: « Automating image creation * Version controlling application configuration + Ensuring consistent builds * Sharing application packaging with others | 9.2 Dockerfile Syntax A Dockerfile uses a simple syntax: # Comments start with # INSTRUCTION arguments Instructions are uppercase, followed by arguments. Here's a minimal Dockerfile: FROM ubuntu:22.04 RUN apt-get update && apt-get install -y nginx CMD ["nginx", "-g", “daemon off;"] Each instruction adds a layer to the image. The order matters because Docker caches layers. Common instructions: « FROM: Base image RUN: Execute commands COPY: Copy files from host ADD: Copy with extra features WORKDIR: Set working directory CMD: Default command 26 Want Linux & DevOps Materials? <> Message to Me for Price Details. « ENTRYPOINT. Main command « EXPOSE: Document ports « ENV: Set environment variables « USER: Set user * ARG: Build-time variables | 9.3 Creating Your First Dockerfile Create a simple Dockerfile for a Python application: Create a file named Docker file in your project directory: FROM python :3.11-slim WORKDIR /app COPY [Link] . RUN pip install --no-cache-dir -r requirements, txt coPY . CMD ["python", “[Link]"] And create a simple [Link] print("Hello, Docker! ") And [Link]: flask This Dockerfile: 1. Starts from a minimal Python 3.11 image 2. Creates a working directory 3. Copies requirements filed. Installs dependencies 4. Copies the rest of the code 5. Sets the default command | 9.4 Building Images with Dockerfile Build an image from a Dockerfile: docker build -t my-app:1.8 . 27 Want Linux & DevOps Materials? <> Message to Me for Price Details. This command: « -t my-app:1.0: Tags the image «. : Build context (current directory) Build with a specific Dockerfile: docker build -f [Link] -t my-app . Specify build arguments: docker build --build-arg VERSION=1.2 -t my-app . View build history: docker history my-app:1.@ | 9.5 Layered Architecture Docker images consist of layers, each created by a Dockerfile instruction. Layers build on each other: Layer 1: FROM ubuntu:22.04 (5MB) Layer 2: RUN apt-get update (10MB) Layer 3: RUN apt-get install -y nginx (5QMB) Layer 4: COPY . /app (2MB) This layering provides several benefits: Caching: If you change only Layer 4, Docker uses cached layers 1-3. This dramatically speeds up builds. Sharing: Multiple images can share the same base layers, saving disk space. Distribution: Docker pushes and pulls only layers that have changed View layers of an image: docker inspect my-app:1.@ | jq '.[@].[Link]' Order matters for caching. Place instructions that change frequently at the bottom. For example, copy requirements and install dependencies before copying code to leverage caching. 28 Want Linux & DevOps Materials? <> Message to Me for Price Details. 10.1 FROM - Base Images FROM specifies the base image to build upon. Every Dockerfile must start with FROM unless it's a scratch image. FROM python:3.11-slim Multi-stage builds use multiple FROM statements: FROM node:18 AS builder # Build application FROM nginx:alpine # Copy built assets Use scratch for completely empty images: FROM scratch COPY my-binary / CMD ["/my-binary" ] Always use specific tags, not latest , for reproducibility. | 10.2 WORKDIR - Working Directory WORKDIR sets the working directory for subsequent instructions: FROM ubuntu :22.04 WORKDIR /app cory . . RUN make WORKDIR /app/bin CMD ["./app"] If the directory doesn't exist, Docker creates it. Multiple WORKDIR instructions can be used WORKDIR /app WORKDIR sre This creates /app/sre . | 10.3 COPY and ADD - Adding Files COPY copies files from the build context: 29 Want Linux & DevOps Materials? <> Message to Me for Price Details. COPY [Link] /app/ COPY . /app/ ADD provides additional features: « Automatic decompression of tar files « Remote URL downloading « Limited pattern matching ADD [Link] /tmp/ ADD [Link] /app/ ADD . /app/ Prefer COPY over ADD when possible. It's more predictable and secure. Use .dockerignore to exclude files: node_modules/ -git/ *.log | 10.4 RUN - Executing Commands RUN executes commands during build, creating a new layer: RUN apt-get update && apt-get install -y curl RUN pip install -r [Link] RUN npm install --production Chain commands to reduce layers: RUN apt-get update && \ apt-get install -y curl vim && \ rm -rf /var/lib/apt/lists/* This is more efficient because each RUN creates a layer. Combining commands reduces layer count and image size. | 10.5 CMD and ENTRYPOINT CMD provides defaults for an executing container: CMD ["python", “[Link]"] CMD ["nginx", “-g", "daemon of f;"] The shell form: 30 Want Linux & DevOps Materials? <> Message to Me for Price Details. CMD python [Link] ENTRYPOINT defines the executable: ENTRYPOINT ["python"] CMD ["[Link]"] When combined * ENTRYPOINT is the command * COND provides arguments This pattern creates flexible images: FROM ubuntu:22.04 ENTRYPOINT ["echo"] CMD ["Hello, World!"] Running without arguments: prints "Hello, World!" Running with arguments: docker run my-image "Custom" prints "Custom" | 10.6 EXPOSE - Port Documentation EXPOSE documents which ports the container listens on: EXPOSE 80 EXPOSE 443 EXPOSE 3008 This doesn't actually publish ports; it's documentation for users and tools: docker run -p 8080:80 -p 443:443 my-image Multiple ports can be exposed: EXPOSE 88 443 3080 | 10.7 ENV - Environment Variables ENV sets environment variables: ENV NODE_ENV=production ENV DB_HOST=localhost DB_PORT=5432 These variables persist in the container and can be overridden at runtime: 31 Want Linux & DevOps Materials? <> Message to Me for Price Details. docker run -e NODE_ENV=development my-image Use environment variables for configuration: ENV APP_PORT=3808 EXPOSE $APP_PORT CMD ["node", "[Link]"] | 10.8 USER - Running as Non-Root USER changes the user for subsequent instructions: FROM ubuntu :22.04 RUN groupadd -r app && useradd -r -g app app USER app WORKDIR /app COPY --chown=app:app Running as non-root improves security. Create the user before switching. Specify user ID for consistency: USER 1608 :1880 Use numeric IDs for compatibility across systems. | 11.1 The Challenge of Multiple Services Modern applications consist of multiple services: + Frontend (React, Angular, Vue) * Backend API (Node, Python, Java) « Database (PostgreSQL, MySQL) * Cache (Redis) « Message queue (RabbitMQ) Managing each service with separate docker run commands quickly becomes complex. You need to: « Manage startup order * Configure networking between services + Mount volumes for each service 32 Want Linux & DevOps Materials? <> Message to Me for Price Details. « Set environment variables « Handle inter-service communication Docker Compose solves these challenges with a YAML-based configuration. | 11.2 Introduction to Docker Compose Docker Compose is a too! for defining and running multi-container Docker applications. It uses a YAML file to configure: « Services (containers) * Networks + Volumes With a single command ( docker-compose up ), Compose starts all services, creates networks, and mounts volumes as defined. Benefits: * Single configuration file for all services « Simplified networking (containers find each other by service name) « Volume management for data persistence « Environment variable support « Dependency management (start order) | 11.3 Installing Docker Compose Docker Desktop includes Docker Compose automatically. If using Linux, install separately: sudo curl -L "[Link] st/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/1 ocal/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose Verify installation: docker-compose --version For recent versions, Docker Compose is a plugin: docker compose version Both docker-compose (standalone) and docker compose (plugin) work similarly. 33 Want Linux & DevOps Materials? <> Message to Me for Price Details. 11.4 Creating a [Link] File Here's abasic [Link] for a web app with Nginx: version: '3.8' services: web: image: nginx:alpine ports: - "8080:80" volumes : - ,/html: /usr/share/nginx/html This configuration: « Defines a service named web « Uses the Nginx Alpine image « Maps port 8080 on host to 80 in container * Mounts local ./htm1 to the container's web directory Start this service: docker-compose up -d Stop and remove: docker-compose down | 11.5 Starting Multiple Containers Amore realistic example with a web app and Redis: version: '3.8' services: web: build: ports: - "5800:5000" environment : - REDIS_HOST=redis depends_on: - redis volumes : = .t/app 34

También podría gustarte