Home   tech  

why we need docker

To illustrate the benefits of Docker, let's go through a simple example: deploying a Python Flask application using Docker. This example will highlight Docker's advantages in terms of consistency, isolation, portability, and efficiency.

Without Docker: Traditional Deployment

Traditionally, to deploy a Flask application, you would need to:

  1. Ensure that the target environment has the correct version of Python installed.
  2. Install all dependencies listed in your requirements.txt file, hoping there are no conflicts with other applications or services running on the same system.
  3. Configure the web server and possibly a reverse proxy on the target system.
  4. Manage differences across development, testing, and production environments manually, which can lead to inconsistencies and the infamous "it works on my machine" problem.

With Docker: Containerized Deployment

Now, let's see how Docker simplifies this process.

Step 1: Create a Flask Application

First, you create a simple Flask application. Let's name it app.py:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, Docker!'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

Step 2: Define Requirements

Next, you specify your application's dependencies in a requirements.txt file:

Flask==2.0.1

Step 3: Create a Dockerfile

Then, you create a Dockerfile to build your Docker image. The Dockerfile contains instructions for building the image, including the base image, dependencies, and how to run your application.

# Use an official Python runtime as a parent image
FROM python:3.8-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 5000 available to the world outside this container
EXPOSE 5000

# Define environment variable
ENV NAME World

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

Step 4: Build and Run Your Container

Finally, you build your Docker image and run it as a container:

docker build -t flask-tutorial .
docker run -p 4000:5000 flask-tutorial

This builds the Docker image with the tag flask-tutorial and runs it, mapping port 5000 inside the container to port 4000 on your host, making the application accessible on http://localhost:4000.

Benefits Illustrated

Published on: Mar 06, 2024, 12:01 AM  
 

Comments

Add your comment