Setting Up a Dockerized Flask Application with PostgreSQL
In today's fast-paced development landscape, containerization has emerged as a powerful tool for deploying applications efficiently and consistently. Docker, a popular containerization platform, allows developers to package applications along with all their dependencies into containers. In this article, we will explore how to set up a Dockerized Flask application with PostgreSQL, providing you with step-by-step guidance, code examples, and troubleshooting tips.
What is Flask?
Flask is a lightweight web framework for Python that allows developers to build web applications quickly and with minimal boilerplate. Its simplicity and flexibility make it a popular choice for both small and large-scale projects.
Why Use PostgreSQL?
PostgreSQL is an advanced, open-source relational database management system known for its reliability and robustness. It supports advanced data types and performance optimization features, making it ideal for various applications.
Use Cases for Dockerized Flask and PostgreSQL
- Development Consistency: Ensure that your application runs the same way in development, testing, and production.
- Scalability: Easily scale your application by deploying multiple containers.
- Isolation: Run different applications in separate containers without conflicts between dependencies.
Prerequisites
Before we begin, make sure you have the following installed on your machine: - Docker - Docker Compose - Python 3.x
Step 1: Create the Project Structure
Create a new directory for your project and navigate into it:
mkdir flask-postgres-docker
cd flask-postgres-docker
Inside this directory, create the following structure:
flask-postgres-docker/
│
├── app/
│ ├── __init__.py
│ ├── app.py
│ └── requirements.txt
│
├── Dockerfile
└── docker-compose.yml
Step 2: Build the Flask Application
requirements.txt
In the app/requirements.txt
file, add the necessary dependencies:
Flask
psycopg2-binary
Flask-SQLAlchemy
app.py
Create a simple Flask application in app/app.py
:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@db:5432/mydatabase'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
@app.route('/users', methods=['POST'])
def create_user():
name = request.json.get('name')
new_user = User(name=name)
db.session.add(new_user)
db.session.commit()
return jsonify({'id': new_user.id, 'name': new_user.name}), 201
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{'id': user.id, 'name': user.name} for user in users])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Step 3: Create the Dockerfile
In the root directory, create a Dockerfile
to define the image for your Flask application:
# Use the official Python image
FROM python:3.9-slim
# Set the working directory
WORKDIR /app
# Copy the requirements file and install dependencies
COPY app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code
COPY app/ .
# Expose the port where the app runs
EXPOSE 5000
# Command to run the application
CMD ["python", "app.py"]
Step 4: Create the Docker Compose File
Now, create a docker-compose.yml
file for managing the services:
version: '3.8'
services:
db:
image: postgres:latest
environment:
POSTGRES_DB: mydatabase
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
web:
build: .
ports:
- "5000:5000"
depends_on:
- db
Step 5: Build and Run the Application
With everything in place, you can now build and run your Docker containers. Execute the following command in your project directory:
docker-compose up --build
This command will build the Docker images and start the application and PostgreSQL database. You should see output indicating that the Flask app is running on http://localhost:5000
.
Step 6: Interacting with the Application
You can interact with your Flask application using tools like curl
or Postman.
Creating a User
To create a new user, execute the following curl
command:
curl -X POST http://localhost:5000/users -H "Content-Type: application/json" -d '{"name": "John Doe"}'
Retrieving Users
To retrieve the list of users, use:
curl http://localhost:5000/users
Troubleshooting Common Issues
- Database Connection Issues: Ensure that the PostgreSQL service is running and the connection URI is correct.
- Flask Not Starting: Check for any syntax errors in your Python files.
- Data Not Persisting: Make sure your database is correctly set up and the connection details are accurate.
Conclusion
In this article, we've walked through the process of setting up a Dockerized Flask application with PostgreSQL. By leveraging Docker and Docker Compose, you can create a consistent and scalable development environment. This setup not only makes deployment easier but also enhances collaboration among teams. Happy coding!