Run flask on docker with postgres and guinicorn

Step 1: Create a Flask App

# app.py
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(message='Hello, Flask and Docker!')

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

Step 2: Create a requirements.txt file

Flask==2.0.1
gunicorn==20.1.0
psycopg2==2.9.1

Step 3: Create a Dockerfile

# Use an official Python runtime as a parent image
FROM python:3.8-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["gunicorn", "-b", "0.0.0.0:80", "app:app"]

Step 4: Create a docker-compose.yml file

version: '3'
services:
  web:
    build: .
    ports:
     - "5000:80"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mydatabase
    depends_on:
      - db
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mydatabase

Step 5: Run the Docker Compose

docker-compose up

This will start your Flask app with Gunicorn server and PostgreSQL database using Docker Compose. Access the app at http://localhost:5000.