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:
Create a Directory Structure: Create a directory for your project and navigate into it:
mkdir docker-python-appcd docker-python-appzCreate the Python Web Application: Create a Python file named
app.pywith the following code:from flask import Flaskapp = Flask(__name__)def hello():return "Hello, Docker!"if __name__ == '__main__':app.run(host='0.0.0.0', port=8080)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 imageFROM python:3.8-slim# Set the working directory to /appWORKDIR /app# Copy the current directory contents into the container at /appCOPY . /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 containerEXPOSE 8080# Define environment variableENV NAME World# Run app.py when the container launchesCMD ["python", "app.py"]Create a Requirements File: Create a file named
requirements.txtwith the following content:Flask==2.0.1Build the Docker Image: Build the Docker image using the following command:
docker build -t python-docker-app .Run the Docker Container: Run the Docker container from the image you built:
docker run -p 8080:8080 python-docker-appAccess the Web Application: Open a web browser and navigate to
http://localhost:8080to 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.
