Dockerize Simple Python Flask App
In this article, we will show you how to containerize a simple Python Flask app using Docker.
Prerequisites
Before you begin, make sure you have Docker installed on your machine. You can download and install Docker from the official website here.
Step 1: Create a Python Flask App
First, let’s create a simple Python Flask app. Create a file named app.py
with the following code:
“`python
from flask import Flask
app = Flask(__name__)
@app.route(‘/’)
def hello_world():
return ‘Hello, Docker!’
“`
Step 2: Create a Requirements File
Create a file named requirements.txt
and add the following line:
“`txt
flask
“`
Step 3: Create a Dockerfile
Create a file named Dockerfile
in the root directory of your project and add the following code:
“`Dockerfile
FROM python:3
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD [“python”, “app.py”]
“`
Step 4: Build the Docker Image
Open a terminal and navigate to the root directory of your project. Run the following command to build the Docker image:
“`bash
docker build -t flask-app .
“`
Step 5: Run the Docker Container
Once the image is built, you can run the Docker container using the following command:
“`bash
docker run -d -p 5000:5000 flask-app
“`
Now you can access your Flask app at http://localhost:5000
.
Conclusion
You have successfully containerized a simple Python Flask app using Docker. You can now easily deploy and run your app in any environment that supports Docker.