Home > Net >  Python Flask - volumes don't work after dockerizing
Python Flask - volumes don't work after dockerizing

Time:02-05

I'm trying to dockerize a Python-Flask application, using also volumes in order to have a live update when I change the code, but volumes don't work and I have to stop the containers and open run it again. That is the code that I try to change (main.py):

from flask import Flask
import pandas as pd
import json
import os

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello"

My dockerfile.dev:

FROM python:3.9.5-slim-buster
WORKDIR '/app'

COPY requirements.txt .

RUN pip3 install -r requirements.txt
RUN pip install python-dotenv


COPY ./ ./

ENV FLASK_APP=main.py

EXPOSE 5000

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

My docker-compose.yaml

version: "3"

services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "5000:5000"
    expose: 
      - "5000"
    volumes:
      - .:/app
    stdin_open: true
    environment:
        - CHOKIDAR_USEPOLLING=true
        
        - PGHOST=db
        - PGUSER=userp
        - PGDATABASE=p
        - PGPASSWORD=pgpwd
        - PGPORT=5432
        
        - DB_HOST=db
        - POSTGRES_DB=p
        - POSTGRES_USER=userp
        - POSTGRES_PASSWORD=pgpwd

    depends_on:
      - db

  db:
      image: postgres:latest
      restart: always
      environment:
          - POSTGRES_DB=db
          - DB_HOST=127.0.0.1
          - POSTGRES_USER=userp
          - POSTGRES_PASSWORD=pgpwd
          - POSTGRES_ROOT_PASSWORD=pgpwd
      volumes:
          - db-data-p:/var/lib/postgresql/data

  pgadmin-p:
    container_name: pgadmin4_container_p
    image: dpage/pgadmin4
    restart: always
    environment:
      PGADMIN_DEFAULT_EMAIL: [email protected]
      PGADMIN_DEFAULT_PASSWORD: root
    ports:
      - "5050:80"
    logging:
      driver: none

volumes:
  db-data-p:

To start I execute docker-compose up

Volume /app seems not works

CodePudding user response:

Flask does not reload files by default. You need to enable that explicitly e.g. by passing --debug on the flask command line:

python3 -m  flask --debug run --host=0.0.0.0

If you modify your Dockerfile to use the --debug flag...

CMD [ "python3", "-m" , "flask", "--debug", "run", "--host=0.0.0.0"]

...then it will work as you expect. You could also set the FLASK_DEBUG environment variable instead of using the --debug flag:

services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "5000:5000"
    volumes:
      - .:/app
    environment:
      - FLASK_DEBUG=1
  • Related