Deploying a Python Web Application with Docker and Flask

Tiempo de lectura: < 1 minuto

In this tutorial, we will learn how to use Docker to deploy a basic Python web application using the Flask framework. :snake:

Step 1: Project Structure

Create a new folder named “MyAppFlask” in your project directory and navigate to it:

mkdir ~/projects/MyAppFlask
cd ~/projects/MyAppFlask

Step 2: Flask Application Code

Create a file named app.py with the following code for our simple Flask application:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Docker and Flask!'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

Step 3: Dockerfile

Create a file named Dockerfile in the same folder with the following content:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD ["python", "app.py"]

Step 4: requirements.txt

Create a file named requirements.txt with the following content:

Flask==2.0.1

Step 5: Build Docker Image

In your terminal, run the following command to build the Docker image:

docker build -t my-flask-app .

Step 6: Start Container

Now, run the following command to start the container:

docker run -p 5000:5000 -d --name my-app-container my-flask-app

Step 7: Access the Application

Open your browser and visit http://localhost:5000 to see your Flask application in action.

Step 8: Share and Enjoy

Share your success on social media! Challenge others to follow this tutorial and deploy their own Flask application with Docker.

Leave a Comment