Create and Run a Container for a Python Web Application.

Task: Create and Run a Docker Container for a Python Web Application

Description: You are tasked with creating and running a Docker container for a simple Python web application using Flask. The application should display a "Hello, Docker!" message when accessed through a web browser.

Steps:

  1. Create a Directory Structure: Create a directory for your project and navigate into it:

    mkdir docker-python-app
    cd docker-python-appz
  2. Create the Python Web Application: Create a Python file named app.py with the following code:

    from flask import Flask
    app = Flask(__name__)
    @app.route('/')
    def hello():
    return "Hello, Docker!"
    if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
  3. Create a Dockerfile:

    Create a file named Dockerfile (without any file extension) in the same directory with the following content:

    # Use an official Python runtime as a parent image
    FROM python:3.8-slim
     
    # Set the working directory to /app
    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 8080 available to the world outside this container
    EXPOSE 8080
     
    # Define environment variable
    ENV NAME World
     
    # Run app.py when the container launches
    CMD ["python", "app.py"]
  4. Create a Requirements File: Create a file named requirements.txt with the following content:

    Flask==2.0.1
  5. Build the Docker Image: Build the Docker image using the following command:

    docker build -t python-docker-app .
  6. Run the Docker Container: Run the Docker container from the image you built:

    docker run -p 8080:8080 python-docker-app
  7. Access the Web Application: Open a web browser and navigate to http://localhost:8080 to see the "Hello, Docker!" message.

Remember that this is a basic example, and there are many additional considerations and optimizations you can apply when working with Docker containers in real-world scenarios.

You should also read: