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-app
cd docker-python-appz
Create the Python Web Application: Create a Python file named
app.py
with the following code:from flask import Flask
app = 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 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"]
Create a Requirements File: Create a file named
requirements.txt
with the following content:Flask==2.0.1
Build 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-app
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.