Containerization Made Easy: A Beginner's Guide to Docker

Containerization Made Easy: A Beginner's Guide to Docker

Containers have become an integral part of DevOps in recent years. They have changed the way software is developed, deployed, and managed. Containers allow developers to package an application with all of its dependencies and configurations, making it easy to deploy and run consistently across different environments. Let's understand containers in detail💁

What are Containers? 🤔

Alternatives to Docker Container - Mobilise Cloud

Containers are a lightweight and portable way to package an application and its dependencies. They isolate the application from the underlying infrastructure, allowing it to run consistently across different environments, from development to production. Containers are based on the concept of operating system virtualization, where each container shares the same host operating system but has its own isolated file system, network, and process space.

Containers vs. Virtual Machines

Demystifying containers, Docker, and Kubernetes - Microsoft Open Source Blog

Containers are often compared to virtual machines (VMs), but they are different in many ways. VMs require a hypervisor to virtualize the hardware, which means that each VM requires a full operating system, including its own kernel, to run. This makes VMs much heavier and slower than containers, as they require more resources to run. Containers, on the other hand, share the host operating system kernel, which makes them much lighter and faster than VMs.

What is Docker?

Docker is an open-source containerization platform that enables developers to create, deploy, and run applications in portable containers. Docker provides an easy and efficient way to package and distribute applications, which helps to increase development speed, portability, and consistency across different environments. With Docker, developers can ship code faster while reducing the risk of compatibility issues or dependency conflicts.

Docker containers are self-contained, lightweight, and portable execution environments. They package an application and its dependencies into a single image file, which can be deployed to any platform that supports Docker. Docker containers run in an isolated environment, allowing them to be deployed consistently across different infrastructure environments, such as development, testing, and production.

Containerization

Containerization is a method of operating system virtualization. It allows multiple isolated applications or services to run on a single host without interfering with each other. Each container has its own software environment, including the operating system, libraries, and application code.

Using Docker involves several steps:

  1. Writing a Dockerfile

  2. Building a Docker image

  3. Running a Docker container

Benefits of Containers in DevOps

Containers have several benefits in DevOps, including:

  1. Consistent Environments: Containers allow developers to package an application with all of its dependencies and configurations, ensuring that it runs consistently across different environments. This eliminates the "it works on my machine" 🤡 problem, where an application works in one environment but fails in another.

  2. Portability: Containers can be easily moved between different environments👨‍🦽 from development to production. This makes it easy to deploy an application in a new environment without having to worry about configuring the underlying infrastructure.

  3. Scalability: Containers can be easily scaled up or down depending on the demand for the application. This makes it easy to handle traffic spikes and ensures that the application can handle a large number of users.

  4. Faster Deployment: Containers can be deployed much faster than traditional methods🚝. They can be built, tested, and deployed in minutes, which makes the software development process much more efficient.

  5. Resource Efficiency: Containers are much more resource-efficient than VMs, as they require fewer resources to run. This makes them ideal for running multiple applications on a single host.

🌐Now lets us understand how easy it is to containerize any program using docker. In the following example, we will dockerize a Python calculator app and we are going to dockerize it using Dockerfile. After that, we will see what commands are required to build a docker image from the Dockerfile and run it on docker.

Sample Python 3 calculator app

Here's a simple Python calculator program that can perform basic arithmetic operations:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

print("Select operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
    print(num1, "+", num2, "=", add(num1,num2))

elif choice == '2':
    print(num1, "-", num2, "=", subtract(num1,num2))

elif choice == '3':
    print(num1, "*", num2, "=", multiply(num1,num2))

elif choice == '4':
    print(num1, "/", num2, "=", divide(num1,num2))
else:
    print("Invalid choice")

Containerize the Python code using Dockerfile

Here's how you can dockerize the Python calculator program:

  1. First, create a new file called Dockerfile in the same directory as your Python code.

  2. In Dockerfile, start with an official Python image as the base:

     FROM python:3.9-slim-buster
    
  3. Copy your Python code into the image and install any necessary dependencies. In this case, we only need the built-in numpy library, so we will install it using pip:

     WORKDIR /app
     COPY calculator.py requirements.txt /app/
     RUN pip install -r requirements.txt
    
  4. Finally, specify the command that should be run when the container starts up:

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

The completed Dockerfile would look like this:

FROM python:3.9-slim-buster

WORKDIR /app
COPY calculator.py requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt

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

Docker Build and Run

Docker Containers! Oh my!!. How to create a Docker image, deploy a… | by  Todd Caputo | AWS Tip

Build the Docker image using the following command (in the same directory where your Dockerfile and calculator.py files are located):

docker build -t calculator .

This command tells Docker to build a new image using the Dockerfile in the current directory, and name the image calculator. Finally, run a container from the image using the following command:

docker run -it calculator

This command tells Docker to run a new container from the calculator image. The --rm flag tells Docker to automatically remove the container when it is stopped (so you don't accumulate lots of stopped containers), and the -it flags allocate a pseudo-TTY so you can interact with the container. When you run this command, you should see the same menu as before, so you can interact with the calculator just like you did when running the Python code directly.

You can now test the calculator program and check the outputs for the Python code. First, make sure you're in your terminal and have Docker installed.

  1. List all running containers using the command docker ps:

     docker ps -a
    

    This command will display all containers that are currently running on your system. You should see a table with columns like CONTAINER ID, IMAGE, COMMAND, CREATED, STATUS, PORTS, and NAMES.

  2. To stop the container do the following:
    To stop a container by name, use this command, replacing container_name with the name of the container you want to stop:

docker stop container_name

Alternatively, to stop a container by its ID, use the following command, replacing container_id with the ID of the container you want to stop:

docker stop container_id

After running the docker stop command, you can verify that the container has stopped by running docker ps again. You should no longer see the stopped container in the output. You can also use docker ps -a.

Conclusion

We successfully dockerized our Python program and were able to run it on the docker container. Containers have revolutionized the way software is developed, deployed, and managed. They have several benefits in DevOps, including consistent environments, portability, scalability, faster deployment, and resource efficiency. As the software development process continues to evolve, containers will play an increasingly important role in DevOps.