Table of Contents
Setting up a Flask application within Docker is an excellent way to ensure consistency across development, testing, and production environments. This tutorial provides a step-by-step guide for beginners to create a Dockerized Flask app from scratch.
Prerequisites
- Basic knowledge of Python and Flask
- Docker installed on your machine
- Text editor or IDE (e.g., VS Code)
- Terminal or command prompt access
Step 1: Create Your Flask Application
First, set up a directory for your project and create a simple Flask app.
Open your terminal and run:
mkdir flask-docker-app
Navigate into the directory:
cd flask-docker-app
Create a Python file named app.py with the following content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask in Docker!'
Save the file.
Step 2: Create requirements.txt
List your Python dependencies in a requirements.txt file:
Flask==2.2.3
Step 3: Write the Dockerfile
Create a Dockerfile in the same directory with the following content:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]
Step 4: Build and Run the Docker Container
Build your Docker image:
docker build -t flask-app .
Run the container:
docker run -d -p 5000:5000 --name my-flask-app flask-app
Step 5: Access Your Flask App
Open your browser and navigate to http://localhost:5000. You should see the message: Hello, Flask in Docker!
Additional Tips
- Use
docker psto check running containers - Stop the container with
docker stop my-flask-app - Remove the container with
docker rm my-flask-app - For development, consider using
docker-composefor easier management
Conclusion
Dockerizing your Flask application simplifies deployment and ensures consistency across environments. Follow these steps to set up your own Flask app with Docker and expand from here for more complex projects.