2022-06-14

Deploying Flask and PostgreSQL with Docker Compose

Deploying Flask and PostgreSQL with Docker Compose

In this article, I will walk you through an example use case of deploying a Flask web application backed by a PostgreSQL database using Docker Compose.

Directory structure is as follows:

flask_app/
  ├── app/
  │   ├── __init__.py
  │   ├── main.py
  │   └── templates/
  │       └── index.html
  ├── Dockerfile
  ├── docker-compose.yml
  └── requirements.txt

Defining Containers

  1. Create a simple Flask application (app/main.py):
app/main.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
  1. Create a basic template for the Flask application (app/templates/index.html):
app/templates/index.html
<!DOCTYPE html>
<html>
<head>
  <title>Flask App with PostgreSQL</title>
</head>
<body>
  <h1>Welcome to our Flask app with PostgreSQL</h1>
</body>
</html>
  1. Create a Dockerfile for the Flask application:
Dockerfile
FROM python:3.9-slim

WORKDIR /app

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

COPY app app

CMD ["python", "app/main.py"]
  1. Add the required Python packages to the requirements.txt file:
requirements.txt
Flask==2.1.1
gunicorn==20.1.0
  1. Create a docker-compose.yml file to define the Flask application and PostgreSQL services:
docker-compose.yml
version: '3.9'

services:
  web:
    build: .
    ports:
      - "5000:5000"
    depends_on:
      - db
  db:
    image: postgres:13-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: flask_db
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:

In this example, we defined two services: web and db. The web service is our Flask application, built from the current directory's Dockerfile. The db service uses the official PostgreSQL image and includes environment variables for user, password, and database name. We also created a named volume (db_data) to persist the PostgreSQL data.

Running Containers

To deploy this Flask application with PostgreSQL:

  1. Build the Docker images:
bash
$ docker-compose build
  1. Start the services and create containers:
bash
$ docker-compose up -d

Now, you can access the Flask application at http://localhost:5000. The application will display a simple "Welcome to our Flask app with PostgreSQL" message.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!