Django celery cannot import name 'Celery' from 'celery' after rebuilding Dockerfile - django

I run Django and Celery in Docker. It's working fine, but after I restart Docker, celery can't start because of import name error.
Errors below:
v_web | Traceback (most recent call last):
v_web | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv
v_web | self.execute(*args, **cmd_options)
v_web | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 393, in execute
v_web | self.check()
v_web | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 423, in check
v_web | databases=databases,
v_web | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 76, in run_checks
v_web | new_errors = check(app_configs=app_configs, databases=databases)
v_web | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 100, in check_url_settings
v_web | value = getattr(settings, name)
v_web | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__
v_web | self._setup(name)
v_web | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup
v_web | self._wrapped = Settings(settings_module)
v_web | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__
v_web | mod = importlib.import_module(self.SETTINGS_MODULE)
v_web | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
v_web | return _bootstrap._gcd_import(name[level:], package, level)
v_web | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
v_web | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
v_web | File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
v_web | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
v_web | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
v_web | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
v_web | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
v_web | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
v_web | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
v_web | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
v_web | File "/app/notification/__init__.py", line 1, in <module>
v_web | from .celery import app as celery_app
v_web | File "/app/notification/celery.py", line 2, in <module>
v_web | from celery import Celery
v_web | ImportError: cannot import name 'Celery' from 'celery' (/usr/local/lib/python3.7/site-packages/celery/__init__.py)
Here's my project structure:
notifications
notification
__init__.py
celery.py
Here's my init.py file:
from .celery import app as celery_app
__all__ = ("celery_app",)
Here's my celery.py:
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "notification.settings")
app = Celery("notification")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
Here's my docker file:
version: "3.9"
services:
redis:
container_name: v_redis
image: redis:alpine
restart: always
db:
container_name: v_db
image: postgres
volumes:
- ./data/db:/var/lib/postgresql/data
env_file:
- ./production.env
restart: always
web:
container_name: v_web
build: .
command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --no-input && gunicorn notification.wsgi:application --limit-request-line 0 --workers=4 --threads=4 --worker-class=gthread --bind 0.0.0.0:8000"
env_file:
- ./production.env
volumes:
- .:/app
- ./staticfiles:/staticfiles
expose:
- 8000
depends_on:
- db
- redis
restart: always
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/"]
interval: 30s
timeout: 10s
retries: 5
celery:
container_name: v_celery
build: .
command: celery -A notification worker -l info --concurrency 4
env_file:
- ./production.env
# volumes:
# - ./redis/:/usr/src/app/
depends_on:
web:
condition: service_healthy
redis:
condition: service_started
restart: always
celery-beat:
container_name: v_celery_beat
build: .
command: celery -A notification beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler
env_file:
- ./production.env
# volumes:
# - ./redis/:/usr/src/app/
depends_on:
- redis
restart: always
flower:
container_name: v_celery_flower
image: mher/flower
command: celery flower
environment:
- CELERY_BROKER_URL=redis://redis:6379/0
- FLOWER_PORT=5555
ports:
- 5555:5555
depends_on:
- redis
restart: always
nginx:
container_name: v_nginx
build: ./nginx
volumes:
- ./staticfiles:/staticfiles
# - ./nginx/nginx.conf:/etc/nginx/nginx.conf
ports:
- 80:80
- 443:443
depends_on:
- web
restart: always
My Dockerfile:
# syntax=docker/dockerfile:1
FROM python:3.7
WORKDIR /app
COPY . /app/
RUN pip install -r requirements.txt
My requirements.txt:
Django>=3.0,<4.0
gunicorn==20.1.0
psycopg2-binary>=2.8
django-crispy-forms
django-celery-beat
django-select2
django-redis
slack_sdk
PyMuPDF
Pillow
google-api-python-client
google-auth-oauthlib
oauth2client
pandas
celery==5.1.2
redis==3.5.3
sqlalchemy
sshtunnel
matplotlib
boto3
I don't know why it fails after rebuilding Dockerfile. Please help. Thanks.

this error is a bug that occur only with python 3.7 (the same version you're using) because the latest release of importlib-metadata .
just downgrade importlib-metadata<5.0 : pip install importlib-metadata==4.13.0

Related

ModuleNotFoundError when trying to get my django project to run in ebs

I am following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html
As it states I created a django.config file in .ebextensions/django.config
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: matador-web.wsgi:application
wsgi.py:
"""
WSGI config for matador_web project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'matador_web.settings')
application = get_wsgi_application()
In settings.py I have:
WSGI_APPLICATION = 'matador_web.wsgi.application'
In var/logs/webstdout.log:
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
Aug 8 06:15:50 ip-172-31-29-222 web: worker.init_process()
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process
Aug 8 06:15:50 ip-172-31-29-222 web: super().init_process()
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process
Aug 8 06:15:50 ip-172-31-29-222 web: self.load_wsgi()
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
Aug 8 06:15:50 ip-172-31-29-222 web: self.wsgi = self.app.wsgi()
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi
Aug 8 06:15:50 ip-172-31-29-222 web: self.callable = self.load()
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
Aug 8 06:15:50 ip-172-31-29-222 web: return self.load_wsgiapp()
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
Aug 8 06:15:50 ip-172-31-29-222 web: return util.import_app(self.app_uri)
Aug 8 06:15:50 ip-172-31-29-222 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app
Aug 8 06:15:50 ip-172-31-29-222 web: mod = importlib.import_module(module)
Aug 8 06:15:50 ip-172-31-29-222 web: File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
Aug 8 06:15:50 ip-172-31-29-222 web: return _bootstrap._gcd_import(name[level:], package, level)
Aug 8 06:15:50 ip-172-31-29-222 web: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
Aug 8 06:15:50 ip-172-31-29-222 web: File "<frozen importlib._bootstrap>", line 991, in _find_and_load
Aug 8 06:15:50 ip-172-31-29-222 web: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
Aug 8 06:15:50 ip-172-31-29-222 web: ModuleNotFoundError: No module named 'matador_web.wsgi'

Gunicorn not starting anymore after adding PostgreSQL in Docker

I have a Django project that I'm trying to dockerize. I successfully added Django with gunicorn and nginx to Docker. However, when trying to add PostgreSQL, I encountered an issue. My Postgres container starts, but my gunicorn one doesn't start anymore, and I get this error in the logs, so it indeed seems like it comes from Postgres :
C:\Users\stephane.bernardelli>docker logs testapp-django_gunicorn-1
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
self.connect()
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/manage.py", line 22, in <module>
main()
File "/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 91, in handle
self.check(databases=[database])
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check
all_issues = checks.run_checks(
File "/usr/local/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/usr/local/lib/python3.10/site-packages/django/core/checks/model_checks.py", line 36, in check_all_models
errors.extend(model.check(**kwargs))
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1461, in check
*cls._check_indexes(databases),
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1864, in _check_indexes
connection.features.supports_covering_indexes
File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/features.py", line 84, in is_postgresql_11
return self.connection.pg_version >= 110000
File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 354, in pg_version
with self.temporary_connection():
File "/usr/local/lib/python3.10/contextlib.py", line 135, in __enter__
return next(self.gen)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 639, in temporary_connection
with self.cursor() as cursor:
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 284, in cursor
return self._cursor()
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 260, in _cursor
self.ensure_connection()
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 243, in ensure_connection
with self.wrap_database_errors:
File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
self.connect()
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
I tried changing the host IP address of postgres in my settings, but it only changed the error, but didn't solve it.
Here is my docker-compose.yml:
version: '3.8'
services:
rabbitmq3:
image: rabbitmq:3-alpine
ports:
- 5672:5672
networks:
- main
postgres:
container_name: postgres
hostname: postgres
image: postgres:latest
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=Scripts Application
networks:
- main
ports:
- "5432:5432"
restart: on-failure
volumes:
- postgresql-data:/var/lib/postgresql/data
django_gunicorn:
volumes:
- static:/static
- media:/media
env_file:
- env
build:
context: .
ports:
- "8000:8000"
command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000"
depends_on:
- postgres
networks:
- main
nginx:
build: ./nginx
volumes:
- static:/static
- media:/media
ports:
- "80:80"
depends_on:
- django_gunicorn
networks:
- main
celery:
restart: always
build:
context: .
command: celery -A main worker -P eventlet -c 100 -l INFO
env_file:
- env
depends_on:
- rabbitmq3
- django_gunicorn
- postgres
networks:
- main
networks:
main:
volumes:
postgresql-data:
static:
media:
Dockerfile:
FROM python:3.10.5-alpine
ENV PYTHONUNBEFFERED = 1
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN \
apk add --no-cache postgresql-libs && \
apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \
python3 -m pip install -r requirements.txt --no-cache-dir && \
apk --purge del .build-deps
COPY ./src /app
WORKDIR /app
I have absolutely no idea where the problem could be coming from, so I'd be glad if someone could guide me on how to solve it, thank you in advance !

Docker-compose does not work in docker-machine

I have a cookiecutter-django application with docker that works fine if I run it locally with docker compose -f local.yml up. Now I am trying to deploy it so first I created a docker-machine in my computer (using macOS Catalina) and activated it.
Now, inside the docker-machine, the docker-compose build works fine, but when I run it, the application crashes.
Any idea what can be happening? I have been trying to solve this for almost a week now...
This are my logs when I do docker-compose up in the docker-machine:
Creating network "innovacion_innsai_default" with the default driver
Creating innovacion_innsai_postgres_1 ... done
Creating innovacion_innsai_django_1 ... done
Creating innovacion_innsai_node_1 ... done
Attaching to innovacion_innsai_postgres_1, innovacion_innsai_django_1, innovacion_innsai_node_1
postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_1 | 2020-03-16 08:41:12.473 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2020-03-16 08:41:12.494 UTC [21] LOG: database system was shut down at 2020-03-16 08:31:09 UTC
postgres_1 | 2020-03-16 08:41:12.511 UTC [1] LOG: database system is ready to accept connections
django_1 | PostgreSQL is available
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | psycopg2.errors.UndefinedTable: relation "innovation_sector" does not exist
django_1 | LINE 1: ...n_sector"."id", "innovation_sector"."sector" FROM "innovatio...
django_1 | ^
django_1 |
django_1 |
django_1 | The above exception was the direct cause of the following exception:
django_1 |
django_1 | Traceback (most recent call last):
django_1 | File "manage.py", line 30, in <module>
django_1 | execute_from_command_line(sys.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
django_1 | utility.execute()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
django_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
django_1 | self.execute(*args, **cmd_options)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute
django_1 | self.check()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
django_1 | include_deployment_checks=include_deployment_checks,
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
django_1 | issues.extend(super()._run_checks(**kwargs))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
django_1 | return checks.run_checks(**kwargs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
django_1 | new_errors = check(app_configs=app_configs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
django_1 | all_namespaces = _load_all_namespaces(resolver)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
django_1 | url_patterns = getattr(resolver, 'url_patterns', [])
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns
django_1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 577, in urlconf_module
django_1 | return import_module(self.urlconf_name)
django_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
django_1 | return _bootstrap._gcd_import(name[level:], package, level)
django_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
django_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
django_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
django_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
django_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
django_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
django_1 | File "/app/config/urls.py", line 18, in <module>
django_1 | path("", include("innovacion_innsai.innovation.urls", namespace="innovation")),
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
django_1 | urlconf_module = import_module(urlconf_module)
django_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
django_1 | return _bootstrap._gcd_import(name[level:], package, level)
django_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
django_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
django_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
django_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
django_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
django_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
django_1 | File "/app/innovacion_innsai/innovation/urls.py", line 2, in <module>
django_1 | from innovacion_innsai.innovation import views
django_1 | File "/app/innovacion_innsai/innovation/views.py", line 9, in <module>
django_1 | from .analytics import alimentacion_cases, agro_cases, turismo_cases, movilidad_cases
django_1 | File "/app/innovacion_innsai/innovation/analytics.py", line 17, in <module>
django_1 | for case in Case.objects.filter(sector__sector=sectors[0]):
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 308, in __getitem__
django_1 | qs._fetch_all()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
django_1 | self._result_cache = list(self._iterable_class(self))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
django_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1133, in execute_sql
django_1 | cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
django_1 | return super().execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
django_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
django_1 | return executor(sql, params, many, context)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
django_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | django.db.utils.ProgrammingError: relation "innovation_sector" does not exist
django_1 | LINE 1: ...n_sector"."id", "innovation_sector"."sector" FROM "innovatio...
django_1 | ^
django_1 |
innovacion_innsai_django_1 exited with code 1
node_1 |
node_1 | > innovacion_innsai#1.1.0 dev /app
node_1 | > gulp
node_1 |
node_1 | [08:41:22] Using gulpfile /app/gulpfile.js
node_1 | [08:41:22] Starting 'default'...
node_1 | [08:41:22] Starting 'styles'...
node_1 | [08:41:22] Starting 'scripts'...
node_1 | [08:41:22] Starting 'imgCompression'...
node_1 | [08:41:22] gulp-imagemin: Minified 0 images
This is my local.yml:
version: '3'
volumes:
local_postgres_data: {}
local_postgres_data_backups: {}
services:
django:
build:
context: .
dockerfile: ./compose/local/django/Dockerfile
image: innovacion_innsai_local_django
depends_on:
- postgres
volumes:
- .:/app
env_file:
- ./.envs/.local/.django
- ./.envs/.local/.postgres
ports:
- "8000:8000"
command: /start
postgres:
build:
context: .
dockerfile: ./compose/production/postgres/Dockerfile
image: innovacion_innsai_production_postgres
volumes:
- local_postgres_data:/var/lib/postgresql/data
- local_postgres_data_backups:/backups
env_file:
- ./.envs/.local/.postgres
#Estas dos siguientes lineas las he aƱadido yo luego
ports:
- "5432:5432"
node:
build:
context: .
dockerfile: ./compose/local/node/Dockerfile
image: innovacion_innsai_local_node
depends_on:
- django
volumes:
- .:/app
# http://jdlm.info/articles/2016/03/06/lessons-building-node-app-docker.html
- /app/node_modules
command: npm run dev
ports:
- "3000:3000"
# Expose browsersync UI: https://www.browsersync.io/docs/options/#option-ui
- "3001:3001"
And this is my .postgres file inside the .envs/local folder:
# PostgreSQL
# ------------------------------------------------------------------------------
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=innovacion_innsai
POSTGRES_USER=debug
POSTGRES_PASSWORD=debug
File "/app/innovacion_innsai/innovation/analytics.py", line 17, in <module>
django_1 | for case in Case.objects.filter(sector__sector=sectors[0]):
It means that when django is initializing (the moment it loads the modules) it's doing DB queries on database that has no migrations applied. You need to transform whatever your code is doing on line 17 to run it lazy.

RUN pip install -r requirements.txt does not install requirements in docker container

I am new to django, docker and scrapy and I am trying to run a django app that also uses scrapy (I basically create a django app that is also a scrapy app and try to call a spider from a django view). Despite specifying this scrapy in requirements.txt and running pip from the Dockerfile, the dependencies are not installed in the container prior to running python manage.py runserver 0.0.0.0:8000 and the django app fails during the system checks, resulting in the web container exiting because of the following exception:
| Exception in thread django-main-thread:
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
web_1 | self.run()
web_1 | File "/usr/local/lib/python3.7/threading.py", line 870, in run
web_1 | self._target(*self._args, **self._kwargs)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
web_1 | fn(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
web_1 | self.check(display_num_errors=True)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
web_1 | include_deployment_checks=include_deployment_checks,
web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
web_1 | return checks.run_checks(**kwargs)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
web_1 | new_errors = check(app_configs=app_configs)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
web_1 | all_namespaces = _load_all_namespaces(resolver)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
web_1 | url_patterns = getattr(resolver, 'url_patterns', [])
web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
web_1 | res = instance.__dict__[self.name] = self.func(instance)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns
web_1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
web_1 | res = instance.__dict__[self.name] = self.func(instance)
web_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
web_1 | return import_module(self.urlconf_name)
web_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
web_1 | return _bootstrap._gcd_import(name[level:], package, level)
web_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
web_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
web_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
web_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
web_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
web_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
web_1 | File "/code/composeexample/urls.py", line 21, in <module>
web_1 | path('scrapy/', include('scrapy_app.urls')),
web_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
web_1 | urlconf_module = import_module(urlconf_module)
web_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
web_1 | return _bootstrap._gcd_import(name[level:], package, level)
web_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
web_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
web_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
web_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
web_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
web_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
web_1 | File "/code/scrapy_app/urls.py", line 4, in <module>
web_1 | from scrapy_app import views
web_1 | File "/code/scrapy_app/views.py", line 1, in <module>
web_1 | from scrapy.crawler import CrawlerProcess
web_1 | ModuleNotFoundError: No module named 'scrapy'
I tried using pip3 instead of pip, pip install --no-cache-dir -r requirements.txt, changing the order of the statements in the Dockerfile and I also checked that Scrapy==1.7.3 appears in requirements.txt. Nothing seems to work.
This is my Dockerfile:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
And this is my docker-compose.yml:
version: '3'
services:
db:
image: postgres
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
A little late, but I came across this issue and eventually figured it out (and am putting this here for anyone else who has the same issue).
The first time I tried building my docker image, my requirements.txt didn't contain the required modules. Of course, I added the required modules but nothing seemed to happen, this is because we need to rebuild the container from scratch, otherwise we are just attempting to build the same version again and again.
To rebuild the container with our updated files, we write:
docker-compose rm -f
docker-compose pull
docker-compose up
If that doesn't work, try the same but replace final line with docker-compose up --build -d.
I got this from this answer.
It seems like you are lacking scrapy in your requirements.txt !
I tried to build a minimal version with all of your components. Hope it helps.
test.py
import scrapy
from time import sleep
def main():
while True:
print(scrapy)
sleep(1)
if __name__ == "__main__":
main()
requirements.txt
Scrapy==1.7.3
Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
WORKDIR /code
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY . ./
CMD [ "python3", "test.py" ]
docker-compose.yml
version: '3'
services:
db:
image: postgres
web:
build: .
ports:
- "8000:8000"
depends_on:
- db

Secret Key environment variable not working on Ubuntu. Django, Postgres, Gunicorn, Nginx, Virtualenv

This is the following error I get when I try to run the makemigrations command while my virtualenv is active:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 307, in execute
settings.INSTALLED_APPS
File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/tony/vp/vpenv/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/tony/vp/vp/config/settings/production.py", line 1, in <module>
from .base import *
File "/home/tony/vp/vp/config/settings/base.py", line 22, in <module>
SECRET_KEY = os.environ["VP_SECRET_KEY"]
File "/home/tony/vp/vpenv/lib/python3.5/os.py", line 725, in __getitem__
raise KeyError(key) from None
KeyError: 'VP_SECRET_KEY'
I have set my environment variables inside three locations:
in my virtual environments bin/activate script:
Environment=VP_SECRET_KEY="****"
Environment=VP_DB_PASS="****"
in the .bashrc file:
VP_SECRET_KEY="****"
VP_DB_PASS="****"
and in my gunicorn.service file:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=tony
Environment=VP_SECRET_KEY="****"
Environment=VP_DB_PASS="****"
Group=www-data
WorkingDirectory=/home/tony/vp/vp/
ExecStart=/home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application
[Install]
WantedBy=multi-user.target
Here is how I import it in my settings base.py (i use multiple settings files):
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ["VP_SECRET_KEY"]
when I echo them by using $VP_SECRET_KEY I do get the value returned.
What can cause this problem? could it be that by setting them in multiple locations there is some sort of collission?
The problem is you are viewing a SESSION variable
$ MYNAME=TARUN
$ env
output of env won't show MYNAME because it is a variable in current BASH. So you need to export it
export VP_SECRET_KEY="****"
export VP_DB_PASS="****"
Edit 1
Also if you want you can pass environment variable through gunicorn
ExecStart=/home/tony/vp/vpenv/bin/gunicorn -e VP_SECRET_KEY=***** --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application