2

I have a simple Flask application with the following structure:

|__app     
|  └── __init__.py
|  └── config.py
└── docker-compose.yml
└── Dockerfile

Key here is that __init__.py imports config.py. I use docker-compose to run the application in a container in DEBUG mode, while the end product is a container solely build from the Dockerfile.

The __init__.py file:

from flask import Flask

from .config import config


def create_app(config_name='development'):
    """Create the app."""
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    @app.route('/', methods=['GET'])
    def index():
        return 'hello world' 

    return app

The Dockerfile builds the application in a docker container:

FROM python:3.6-alpine
COPY requirements.txt /
RUN pip install Flask gunicorn
COPY app/ /app
WORKDIR /app
EXPOSE 8000
CMD gunicorn --bind=0.0.0.0:8000 "__init__:create_app()"

The docker-compose.yml is used for development: it shares the app directory so it enables the app to run in DEBUG mode:

version: '3'
services:
  svc1:
    build: .
    entrypoint:
      - flask
      - run
      - --host=0.0.0.0
    environment:
      FLASK_DEBUG: 1
      FLASK_APP: __init__.py
    ports: ['5000:5000']
    volumes: ['./app:/app']

In the main folder you can run the application in debug mode with docker-compose up --build -d and you navigate to localhost:5000 it returns "hello world".

But if you build the image with docker build -t exampleapi . and run the image it complains:

File "/app/init.py", line 3, in module

from .config import config

ImportError: attempted relative import with no known parent package

Community
  • 1
  • 1
Joost Döbken
  • 3,450
  • 2
  • 35
  • 79

1 Answers1

0

As mentioned here, to make the relative import work, one of the easier options is to specify the fully dotted name of the module to Gunicorn, like so:

app.__init__.create_app()

Other options to get this working include:

  • Changing your relative import to a form like from mymodule import as_int. This will only work if your module name is unique. Otherwise, you can:

  • from mypackage.mymodule import as_int

xrisk
  • 3,790
  • 22
  • 45