pythonpostgresqldockerflaskflask-sqlalchemy

http://localhost/5000 not working in docker flask


can't open file '/web/manage.py': [Errno 2] No such file or directory exited with code 2

NOTE: Tried all similar problems solution posted, did not work.

No matter what I do, not able to get http://localhost/5000 to work. Even if the above error goes away by removing volume and command from docker-container.

Below is docker-compose.yml


services:
  web:
    build: ./web
    command: python /web/manage.py runserver 0.0.0.0:8000
    volumes:
      - './users:/usr/src/app'
 
    ports:
      - 5000:5000 
    env_file:
      - ./.env.dev 

Below is Dockerfile:

# pull official base image
FROM python:3.9.5-slim-buster

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt

# copy project
COPY . /usr/src/app/

BELOW IS manage.py:

from flask.cli import FlaskGroup
from project import app
cli = FlaskGroup(app)
if __name__ == "__main__":
    cli()

BELOW IS init.py:

from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def hello_world():
    return jsonify(hello="world")

Below is the structure:

The ones marked in red appeared when I ran this command: docker-compose build enter image description here


Solution

  • A couple of changes to do.

    The cli command in your docker-compose.yml file needs to be:

        command: python /usr/src/app/manage.py run -h 0.0.0.0 -p 8000
    

    There the command name is run and not runserver. Also the host ip to bind and port to listen are configured as different command options.

    Also the configured port mapping for the service needs to map to the container port from the command:

        ports:
          - 5000:8000 
    

    In your manage.py module, FlaskGroup should be provided create_app option which is factory not the app instance. You can implement this as a lambda function.

    cli = FlaskGroup(create_app=(lambda:app))
    

    Edit

    The source files are not mounted in the container volume that why you're getting "no such file manage.py".

    You need to mount your source files in the container volume under /usr/src/app.

    volumes:
      - './web:/usr/src/app'