Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Docker Ep 9: The Building Blocks – Detailed Structure of a Dockerfile

15 August 2024 at 11:51

Alex now knows the basics, but it’s time to get their hands dirty by writing an actual Dockerfile.

The FROM Instruction: Choosing the Foundation

The first thing Alex learns is the FROM instruction, which sets the base image for their container. It’s like choosing the foundation for a house.

  • Purpose:
    • The FROM instruction initializes a new build stage and sets the Base Image for subsequent instructions.
  • Choosing a Base Image:
    • Alex decides to use a Python base image for their application. They learn that python:3.9-slim is a lightweight version, saving space and reducing the size of the final image.

FROM python:3.9-slim

Example: Think of FROM as picking the type of bread for your sandwich. Do you want white, whole wheat, or maybe something gluten-free? Your choice sets the tone for the rest of the recipe.

The LABEL Instruction: Adding Metadata (Optional)

Next, Alex discovers the LABEL instruction. While optional, it’s a good practice to include metadata about the image.

  • Purpose:
    • The LABEL instruction adds metadata like version, description, or maintainer information to the image.
  • Example:
    • Alex decides to add a maintainer label:

LABEL maintainer="alex@example.com"

Story Note: This is like writing your name on a sandwich wrapper, so everyone knows who made it and what’s inside.

The RUN Instruction: Building the Layers

The RUN instruction is where Alex can execute commands inside the image, such as installing dependencies.

  • Purpose:
    • The RUN instruction runs any commands in a new layer on top of the current image and commits the results.
  • Example:
    • To install the Flask framework, Alex writes:

RUN pip install flask

They also learn to combine commands to reduce layers:


RUN apt-get update && apt-get install -y curl

Story Note: Imagine slicing tomatoes and cheese for your sandwich and placing them carefully on top. Each ingredient (command) adds a layer of flavor.

The COPY and ADD Instructions: Bringing in Ingredients

Now, Alex needs to bring their application code into the container, which is where the COPY and ADD instructions come into play.

  • COPY:
    • The COPY instruction copies files or directories from the host filesystem into the container’s filesystem.
  • ADD:
    • The ADD instruction is similar to COPY but with additional features, like extracting compressed files.
  • Example:
    • Alex copies their application code into the container:

COPY . /app

Story Note: This is like moving ingredients from your fridge (host) to the counter (container) where you’re preparing the sandwich.

The WORKDIR Instruction: Setting the Workspace

Alex learns that setting a working directory makes it easier to manage paths within the container.

  • Purpose:
    • The WORKDIR instruction sets the working directory for subsequent instructions.
  • Example:
    • Alex sets the working directory to /app:

WORKDIR /app

Story Note: This is like setting up a designated area on your counter where you’ll assemble your sandwich—keeping everything organized.

The CMD and ENTRYPOINT Instructions: The Final Touch

Finally, Alex learns how to define the default command that will run when the container starts.

  • CMD:
    • Provides defaults for an executing container, but can be overridden.
  • ENTRYPOINT:
    • Configures a container that will run as an executable, making it difficult to override.
  • Example:
    • Alex uses CMD to specify the command to start their Flask app:

CMD ["python", "app.py"]

Story Note: Think of CMD as the final step in making your sandwich—like deciding to add a toothpick to hold everything together before serving.

Below is an example Dockerfile of a flask application,


# Use an official Python runtime as a parent image
FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

Breakdown of the Dockerfile:

  1. FROM python:3.9-slim:
    • This line specifies the base image. In this case, it uses a slim version of Python 3.9, which is lightweight and sufficient for a simple Flask application.
  2. WORKDIR /app:
    • This sets the working directory inside the container to /app. All subsequent commands will be run inside this directory.
  3. COPY . /app:
    • This copies everything from your current directory on the host machine into the /app directory inside the container.
  4. RUN pip install –no-cache-dir -r requirements.txt:
    • This installs the necessary Python packages listed in the requirements.txt file. The --no-cache-dir option reduces the image size by not caching the downloaded packages.
  5. EXPOSE 80:
    • This makes port 80 available for external access. It’s where the Flask application will listen for incoming requests.
  6. ENV NAME World:
    • This sets an environment variable NAME to “World”. You can access this variable in your Python code.
  7. CMD [“python”, “app.py”]:
    • This tells the container to run the app.py file using Python when it starts.

Example Flask Application (app.py):

To complete the example, here’s a simple Flask application you can use:


from flask import Flask
import os

app = Flask(__name__)

@app.route('/')
def hello():
    name = os.getenv('NAME', 'World')
    return f'Hello, {name}!'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

Example requirements.txt:

And here’s the requirements.txt file listing the dependencies for the Flask app:


Flask==2.0.3

Building and Running the Docker Image:

  1. Build the Docker image using the Dockerfile:
docker build -t my-flask-app .

2. Run the Docker container:


docker run -p 4000:80 my-flask-app
  • This maps port 4000 on your host machine to port 80 in the container.

Open your browser and go to http://localhost:4000, and you should see “Hello, World!” displayed on the page.

You can customize the ENV NAME in the Dockerfile or by passing it as an argument when running the container:


docker run -p 4000:80 -e NAME=Alex my-flask-app

This will display “Hello, Alex!” instead.

Docker Ep 6: Running ‘Hello, World!’ with BusyBox: A Docker Adventure

15 August 2024 at 04:22

Once upon a time in the city of Athipati, there was a young coder named Arivanandham. Arivanandham had recently heard whispers of a magical tool called Docker, which promised to simplify the process of running applications. Eager to learn more, Arivanandham decided to embark on a quest—a quest to run the famous “Hello, World!” using the mysterious BusyBox Docker image.

Today, we’re going to take our first step by creating and running a container. And what better way to start than with a tiny yet powerful image called BusyBox? Let’s dive in and explore how to run our first container using BusyBox.

Step 1: Discovering BusyBox on Docker Hub

Our journey begins at the Docker Hub, the vast library of images ready to be transformed into containers. Let’s search for “BusyBox” on Docker Hub.

Upon searching, you’ll find the official BusyBox repository at the top. BusyBox is renowned for its compact size—about 1 megabyte—which makes it an excellent choice for quick downloads and speedy container spins.

Step 2: Exploring BusyBox Tags

Before we proceed, let’s check out the Tags tab on the BusyBox page. Tags represent different versions of the image. We’re going to pick tag 1.36 for our container. This specific tag will be our guide in this Docker adventure.

Step 3: Setting Up Your Docker Environment

To start, we need to open a terminal. If you’re on Docker for Mac, Docker for Windows, or Linux, you can simply open your default terminal. If you’re using Docker Toolbox, open the Docker Quickstart Terminal.

Step 4: Checking Local Images

When you instruct Docker to create a container, it first checks your local system to see if the image is already available. Let’s verify what images we currently have:

docker images

If this is your first time, you’ll see that there are no images available yet. But don’t worry; we’re about to change that.

Step 5: Running Your First Container

Now, let’s run our first container! We’ll use the docker run command, specifying the BusyBox image and tag 1.36. We’ll also tell Docker to execute a simple command: echo "Hello, World!".

docker run busybox:1.36 echo "Hello, World!"

Here’s what happens next:

  • Docker checks for the BusyBox 1.36 image locally.
  • If it’s not found, Docker will download the image from the remote repository.
  • Once the image is downloaded, Docker creates and runs the container.

And just like that, you should see the terminal output:


Hello, World!

Congratulations! You’ve just run your first Docker container.

Step 6: Verifying the Image Download

Let’s run the docker images command again:

docker images

You’ll now see the BusyBox 1.36 image listed. The image has a unique ID, confirming that it’s stored locally on your system.

Step 7: Running the Container Again

Now that we have the BusyBox image locally, let’s run the same container again:

docker run busybox:1.36 echo "Hello, World!"

This time, notice how quickly the command executes. Docker uses the local image, skipping the download step, and instantly spins up the container.

Step 8: Exploring the Container’s File System

Let’s try something new. We’ll list all the contents in the root directory of the BusyBox container:

docker run busybox:1.36 ls /

You’ll see Docker output the list of all directories and files at the root level of the container.

Step 9: Running a Container in Interactive Mode

To dive deeper, we can run the container in an interactive mode, which allows us to interact with the container as if it were a tiny, isolated Linux system. We’ll use the -i (interactive) and -t (pseudo-TTY) flags:


docker run -it busybox:1.36

Now you’re inside the container! Try running commands like ls to see the contents. You can even create a new file:


touch a.txt
ls

You’ll see a.txt listed in the output. To exit the container, simply type exit.

Step 10: Understanding Container Lifecycle

It’s important to note that once you exit a container, it shuts down. If you run the container again using the same command, Docker spins up a brand-new instance. The file you created earlier (a.txt) won’t be there because each container instance is ephemeral, meaning it doesn’t retain data from previous runs unless you explicitly save it.

And there you have it! You’ve successfully created, explored, and understood your first Docker container using the BusyBox image. This is just the beginning of what you can achieve with Docker. As you continue your journey, you’ll discover how containers can simplify development, testing, and deployment, all while keeping your environment clean and isolated.

Docker Ep 5 : THE Bakery, Recepies, Dough & Cookies – Registry, Repository, Images, Containers

12 August 2024 at 15:59

In the bustling town of Tambaram, there was a famous factory known for its delicious cookies. This factory had a unique and modern way of making and distributing its cookies, using a system inspired by Docker’s architecture.

The Recipe Registry

At the heart of the cookie-making process was the Recipe Registry, a giant digital library that stored all the cookie recipes. This registry was like a magical cookbook, holding secrets to every type of cookie imaginable: chocolate chip, oatmeal raisin, and even double fudge delight.

  • Purpose: The Recipe Registry ensured that everyone had access to the latest and greatest recipes. Bakers from all around the world could upload new recipes or download existing ones to make their own cookies.

The Cookie Repository

Each type of cookie had its own Cookie Repository within the Recipe Registry. These repositories were specialized sections where all the different variations of a particular cookie recipe were stored.

  • Example: The chocolate chip cookie repository contained recipes for classic, vegan, gluten-free, and extra gooey versions. Each version was labeled with a tag, like classic, vegan, or gooey.

The Image: A Perfect Cookie Dough

In the factory, the term “Image” referred to the perfect cookie dough that was ready to be baked into cookies. Each image was a complete package containing the recipe, ingredients, and instructions needed to make the cookies.

  • Characteristics: Just like a Docker image, the cookie dough was consistent and repeatable. No matter how many times you used the recipe, you always got the same delicious dough, ready to be baked.

The Container: Freshly Baked Cookies

Once the cookie dough was prepared, it was placed into a Container, representing a batch of freshly baked cookies. Each container was like a magical oven that turned the dough into cookies.

  • Isolation: Each container baked cookies independently, ensuring that the flavor and quality were perfect every time. Bakers could create multiple containers from the same dough image, producing countless batches of cookies.

The Cookie Delivery System

With the help of the Recipe Registry, Cookie Repository, Images, and Containers, the factory had an efficient Cookie Delivery System. This system allowed the factory to distribute its cookies all over Tambaram and beyond.

  • Scalability: If a bakery needed more cookies, they simply created more containers using the same dough image, ensuring everyone had enough cookies to enjoy.

Let’s try directly in to the concepts,

Registry

  • Definition: A Docker Registry is a storage and content delivery system that holds Docker images.
  • Purpose: It is used to manage where Docker images are stored and distributed from.
  • Examples: Docker Hub (the default public registry), Amazon ECR, Google Container Registry, and Azure Container Registry.
  • Functionality: Registries can be public or private. They store Docker images and provide an interface to push (upload) or pull (download) these images to and from repositories.

Docker Hub is the default public registry used by Docker. Here are examples of Docker Hub registry links:

  • Official Image: docker pull nginx

Community Image: docker pull username/repository:tag

Repository

  • Definition: A Docker Repository is a collection of related Docker images, usually providing different versions of the same application or service.
  • Purpose: Repositories organize and manage multiple images of an application or service.
  • Structure: A repository may contain multiple tagged versions of an image. For example, myapp:latest and myapp:v1.0 might be two tags in the same repository.
  • Functionality: Users can push images to a repository and pull images from a repository. Tags are used to differentiate between different versions of an image.

Official Repositories

Community Repositories

User-Specific Repositories

Images

  • Definition: A Docker Image is a lightweight, standalone, executable package that includes everything needed to run a piece of software: code, runtime, libraries, environment variables, and configuration files.
  • Purpose: Images are used to create containers. They provide a portable and consistent runtime environment.
  • Immutability: Images are immutable; once created, they do not change. If updates are needed, a new image version is created.
  • Layers: Images are built up from a series of layers, where each layer represents an instruction in the image’s Dockerfile.

For example, Dockerfile will comprises of the layers of instructions. https://hub.docker.com/layers/library/postgres/12.20-bullseye/images/sha256-2092f4af9ad9fff76e8d0b7c04d8c62b561e44c21a850d4a028124426046f6fa?context=explore

Sample dockerfile for postgres, https://github.com/docker-library/postgres/blob/805329e7a64fad212a5d4b07abd11238a9beab75/17/bookworm/Dockerfile

Containers

  • Definition: A Docker Container is a runnable instance of a Docker image. It is a lightweight, standalone, and executable package of software that includes everything needed to run it.
  • Purpose: Containers provide a consistent environment for applications, allowing them to run reliably regardless of where they are deployed.
  • Isolation: Containers are isolated from each other and the host system, but they can communicate with each other through well-defined channels.
  • Lifecycle: Containers can be created, started, stopped, moved, or deleted using Docker commands.

Relationship Between Concepts

  • Registry and Repository: A Docker registry can host multiple repositories. Each repository can contain multiple images with different tags.
  • Repository and Images: A repository serves as a namespace for images. For example, myrepo/myapp can contain different image tags like v1.0, v2.0, etc.
  • Images and Containers: Containers are running instances of images. You can run multiple containers from the same image.

The Tale of Magic Kitchen : A Docker Architecture

10 August 2024 at 10:19

Setting the Scene

Once upon a time in the bustling town of Pettai, there was a famous restaurant called ArRahman Hotel. This wasn’t just any ordinary restaurant; it had a Magic Kitchen. The Magic Kitchen had the ability to create different kinds of meals almost instantly, without any confusion or delay. Let’s explore how the restaurant achieved this magical feat.

The Magic Kitchen (Docker Engine)

The heart of the restaurant was the Magic Kitchen, which had a unique power. Just like the Docker Engine, it could take orders and prepare meals consistently and efficiently. The kitchen knew how to handle everything without mixing ingredients or creating chaos, no matter how many orders came in.

The Docker engine comprises of dockerd (docker daemon), Docker Client (docker), REST Api, Container Runtime, Image Management, Networking, Volume management, Security mechanisms, Plugins & Extensions.

The Recipe Book (Docker Images)

In the Magic Kitchen, the chefs relied on a special Recipe Book. This Recipe Book contained detailed instructions on how to prepare each dish. These instructions are like Docker Images.

Each image is a blueprint for creating a meal (or application), containing everything needed to cook it up: the ingredients, the cooking method, and any special tools required.

The Prepped Ingredients – (Docker Containers)

When an order came in, the chefs would use the Recipe Book to gather prepped ingredients from the pantry. These ingredients are similar to Docker Containers. Containers are the actual meals created from the recipes, ready to be served. They are isolated from each other, ensuring that the flavors (or code) don’t mix and cause unwanted results.

The Pantry (Docker Registry)

The Magic Kitchen had a vast pantry where all the ingredients were stored. This pantry represents the Docker Registry. It holds all the images (recipes) that the kitchen might need, ready to be pulled and used whenever required. The registry ensures that every meal is prepared with the correct ingredients.

The Chefs (Docker Daemon)

The chefs in the Magic Kitchen are like the Docker Daemon. They are responsible for reading the recipes, pulling the necessary ingredients from the pantry, and preparing the meals in containers. They handle the entire process, ensuring everything runs smoothly and efficiently.

The Customers (Developers and Users)

The patrons of ArRahman’s are the Developers and Users. They come to the restaurant with various demands, and the kitchen satisfies them quickly and reliably. Developers can focus on creating new recipes without worrying about the cooking process, while users enjoy consistent and delicious meals every time.

The Special Dining Areas (Docker Networks and Volumes)

ArRahman also had special dining areas with unique themes and settings, ensuring each meal was experienced perfectly. These are like Docker Networks and Volumes. Networks allow different containers to communicate, much like guests chatting over dinner. Volumes store data persistently, like special utensils or decor kept for regular guests.

So atlast the docker architecture is,

❌
❌