Containerization is a lightweight form of virtualization that allows you to package applications and their dependencies into a single unit called a container. Containers share the host system's kernel but run in isolated user spaces, making them more efficient than traditional virtual machines.
To demonstrate containerization, let’s create a simple Docker container that runs a basic web server using Python.
Make sure you have Docker installed on your machine. You can follow the installation instructions on the official Docker website.
Create a directory for your project and navigate into it:
mkdir my-container-app
cd my-container-app
Create a file named app.py with the following content:
from http.server import SimpleHTTPRequestHandler, HTTPServer
PORT = 8000
class MyHandler(SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Hello, World!')
httpd = HTTPServer(('', PORT), MyHandler)
print(f'Serving on port {PORT}')
httpd.serve_forever()
In the same directory, create a file named Dockerfile with the following content:
# Use the official Python image from the Docker Hub
FROM python:3.9-slim
# Set the working directory
WORKDIR /app
# Copy the application code to the container
COPY app.py .
# Expose the port the app runs on
EXPOSE 8000
# Command to run the application
CMD ["python", "app.py"]
Run the following command to build your Docker image:
docker build -t my-python-app .
To run your container, execute:
docker run -p 8000:8000 my-python-app
Now, you can access your web server by navigating to http://localhost:8000 in your web browser.
Use Official Images: Always start with official images from Docker Hub to ensure security and reliability.
Keep Images Small: Use lightweight base images to reduce the size of your containers.
app.py file to change the response message from 'Hello, World!' to 'Welcome to My Containerized App!'.app.py that returns the current server time when accessed.