Containerization is a lightweight form of virtualization that allows you to package applications and their dependencies into a single unit called a container. This approach ensures that the application runs consistently across different computing environments.
To illustrate containerization, we will use Docker to create a simple containerized application.
Follow the instructions on the Docker website to install Docker on your machine.
Create a new directory for your project and a file named Dockerfile in it. This file will define your container image.
# Use the official Python image from the Docker Hub
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 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"]
Next, create a file named app.py in the same directory:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run(host='0.0.0.0')
Create a requirements.txt file to specify the dependencies:
Flask
Now you can build and run your Docker container:
# Build the Docker image
docker build -t my-python-app .
# Run the Docker container
docker run -p 4000:80 my-python-app
You can now access your application by navigating to http://localhost:4000 in your web browser.
Best Practice: Always tag your Docker images with meaningful version numbers to keep track of changes. Common Mistake: Forgetting to specify the entry point or command in the Dockerfile, which can lead to containers that do not run as expected.
app.py file to return a different greeting message.requirements.txt, such as requests.app.py to use this new dependency and rebuild the container.docker ps to list running containers.docker images to list available images.docker stop and docker rm commands.