I want my flask server to detect changes in code and reload automatically.
I’m running this on docker container.
Whenever I change something, I have to build and up again the container. I have no idea where’s wrong. This is my first time using flask.
Here’s my tree
├── docker-compose.yml └── web ├── Dockerfile ├── app.py ├── crawler.py └── requirements.txt
from flask import Flask import requests app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello Flask!!' if __name__ == '__main__': app.run(debug = True, host = '0.0.0.0')
version: '2' services: web: build: ./web ports: - "5000:5000" volumes: - ./web:/code
Please give me some advice. Thank you in advance.
Flask supports code reload when in debug mode as you’ve already done. The problem is that the application is running on a container and this isolates it from the real source code you are developing. Anyway, you can share the source between the running container and the host with volumes on your
docker-compose.yaml like this:
Here is the
version: "3" services: web: build: ./web ports: ['5000:5000'] volumes: ['./web:/app']
And here the
FROM python:alpine EXPOSE 5000 WORKDIR app COPY * /app/ RUN pip install -r requirements.txt CMD python app.py
I managed to achieve flask auto reload in docker using docker-compose with the following config:
version: "3" services: web: build: ./web entrypoint: - flask - run - --host=0.0.0.0 environment: FLASK_DEBUG: 1 FLASK_APP: ./app.py ports: ['5000:5000'] volumes: ['./web:/app']
You have to manually specify environment variables and entrypoint in the docker compose file in order to achieve auto reload.
Assuming your file structure is the below:
Dockerfile: (note WORKING DIR)
FROM python:3.6.5-slim RUN mkdir -p /home/project/bottle WORKDIR /home/project/bottle COPY requirements.txt . RUN pip install --upgrade pip --no-cache-dir -r requirements.txt COPY . . CMD ["python", "app.py"]
version: '3' services: web: container_name: web volumes: - './web:/home/project/bottle/' <== Local Folder:WORKDIR build: ./web ports: - "8080:8080"
This is my example:
version: "3.8" services: local-development: build: context: . dockerfile: Dockerfiles/development.Dockerfile ports: - "5000:5000" volumes: - .:/code
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "hello world" if __name__ in "__main__": app.run(host="0.0.0.0", port=5000, debug=True)
debug=True enables Flask to change as your code changes.
Docker already plugs into your fs events to change the code "in the container".
If the compose is running different services (app and rq, for instance) you need to set up the volumes on both, or it won’t work.