Dockerizing a Python Django Web Application, Nginx and Gunicorn - python-3.x

I'm trying to connect Gunicorn to my Django application, by Docker, to serve it as an HTTP server. The build was successful, with no errors. My problem starts in the race. That's the kind of message I get:
[2020-10-01 12:55:18 +0000] [9] [INFO] Starting gunicorn 20.0.4
[2020-10-01 12:55:18 +0000] [9] [INFO] Listening at: http://0.0.0.0:8010 (9)
[2020-10-01 12:55:18 +0000] [9] [INFO] Using worker: sync
[2020-10-01 12:55:18 +0000] [13] [INFO] Booting worker with pid: 13
[2020-10-01 12:55:18 +0000] [13] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()
File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process
self.load_wsgi()
File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
self.wsgi = self.app.wsgi()
File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
return self.load_wsgiapp()
File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
return util.import_app(self.app_uri)
File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app
mod = importlib.import_module(module)
File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'wsgi'
[2020-10-01 12:55:18 +0000] [13] [INFO] Worker exiting (pid: 13)
[2020-10-01 12:55:18 +0000] [9] [INFO] Shutting down: Master
[2020-10-01 12:55:18 +0000] [9] [INFO] Reason: Worker failed to boot.
I know that there are several issues with this same doubt, but I have not been successful in reading them and would like another point of view. The error says that the WSGI module was not found, and I don't know why it can't find it. I believe it is a PATH problem.
This is my tree:
Myproject
├───.pip_cache
├───.vscode
├───backups
├───general_app
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───headers
├───sistem
│ └───__pycache__
│ └───wsgi.py
│ └───urls.py
│ └───settings.py
│ └───asgi.py
├───sistema.egg-info
└───app
├───migrations
│ └───__pycache__
├───util
└───__pycache__
And this is my command on docker to run gunicorn:
(cd .. && gunicorn wsgi:app --user www-data --bind 0.0.0.0:8010 --workers 3) &
nginx -g "daemon off;"
I just try to do this:
(cd .. && gunicorn sistem.wsgi:app --user www-data --bind 0.0.0.0:8010 --workers 3) &
nginx -g "daemon off;"
But the error change to:
ModuleNotFoundError: No module named 'sistem'
I don't understand what may be going on.

Related

Psycopg2.OperationalError: server closed the connection unexpectedly

I tried setting up Odoo and Postgres containers in azure using docker-compose, when running them I have an issue with the server closing the connection,
That's what I get from the log at the start of the Postgres container:
The files belonging to this database system will be owned by the user "postgres".
This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".
Data page checksums are disabled.
fixing permissions on existing directory /tmp ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Etc/UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok
Success. You can now start the database server using:
pg_ctl -D /tmp -l logfile start
initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.
waiting for server to start....2022-10-17 14:27:53.717 UTC [758] LOG: starting PostgreSQL 13.8 (Debian 13.8-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
2022-10-17 14:27:53.735 UTC [758] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-10-17 14:27:53.761 UTC [759] LOG: database system was shut down at 2022-10-17 14:27:46 UTC
2022-10-17 14:27:53.774 UTC [758] LOG: database system is ready to accept connections
done
server started
/usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
waiting for server to shut down...2022-10-17 14:27:53.985 UTC [758] LOG: received fast shutdown request
.2022-10-17 14:27:53.999 UTC [758] LOG: aborting any active transactions
2022-10-17 14:27:54.006 UTC [758] LOG: background worker "logical replication launcher" (PID 765) exited with exit code 1
2022-10-17 14:27:54.007 UTC [760] LOG: shutting down
2022-10-17 14:27:54.090 UTC [758] LOG: database system is shut down
done
server stopped
PostgreSQL init process complete; ready for start up.
2022-10-17 14:27:54.241 UTC [696] LOG: starting PostgreSQL 13.8 (Debian 13.8-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
2022-10-17 14:27:54.242 UTC [696] LOG: listening on IPv4 address "0.0.0.0", port 5432
2022-10-17 14:27:54.242 UTC [696] LOG: listening on IPv6 address "::", port 5432
2022-10-17 14:27:54.267 UTC [696] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-10-17 14:27:54.307 UTC [770] LOG: database system was shut down at 2022-10-17 14:27:54 UTC
2022-10-17 14:27:54.317 UTC [696] LOG: database system is ready to accept connections
Then that is the resulting logs from the Odoo container :
2022-10-17 14:27:02,735 445 INFO ? odoo: Odoo version 15.0-20221012
2022-10-17 14:27:02,735 445 INFO ? odoo: Using configuration file at
/etc/odoo/odoo.conf 2022-10-17 14:27:02,735 445 INFO ? odoo: addons
paths: ['/usr/lib/python3/dist-packages/odoo/addons',
'/var/lib/odoo/addons/15.0', '/mnt/extra-addons'] 2022-10-17
14:27:02,735 445 INFO ? odoo: database: odoo#db:5432 2022-10-17
14:27:02,960 445 INFO ? odoo.addons.base.models.ir_actions_report:
Will use the Wkhtmltopdf binary at /usr/local/bin/wkhtmltopdf
2022-10-17 14:27:03,367 445 INFO ? odoo.service.server: HTTP service
(werkzeug) running on localhost:8069 Exception in thread
odoo.service.cron.cron0: Traceback (most recent call last): File
"/usr/lib/python3/dist-packages/odoo/service/server.py", line 445, in
cron_thread
pg_conn.poll() psycopg2.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run() File "/usr/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs) File "/usr/lib/python3/dist-packages/odoo/service/server.py", line 473, in
target
self.cron_thread(i) File "/usr/lib/python3/dist-packages/odoo/service/server.py", line 457, in
cron_thread
thread.start_time = None File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 162, in exit
self.close() File "", line 2, in close File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 90, in check
return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 379, in close
return self._close(False) File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 405, in _close
self.rollback() File "", line 2, in rollback File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 90, in
check
return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 484, in rollback
result = self._cnx.rollback() psycopg2.InterfaceError: connection already closed Exception in thread odoo.service.cron.cron1: Traceback
(most recent call last): File
"/usr/lib/python3/dist-packages/odoo/service/server.py", line 445, in
cron_thread
pg_conn.poll() psycopg2.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run() File "/usr/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs) File "/usr/lib/python3/dist-packages/odoo/service/server.py", line 473, in
target
self.cron_thread(i) File "/usr/lib/python3/dist-packages/odoo/service/server.py", line 457, in
cron_thread
thread.start_time = None File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 162, in exit
self.close() File "", line 2, in close File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 90, in check
return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 379, in close
return self._close(False) File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 405, in _close
self.rollback() File "", line 2, in rollback File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 90, in
check
return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 484, in rollback
result = self._cnx.rollback() psycopg2.InterfaceError: connection already closed
When I check the postgres logs again cause the connection was open the
1st time, i get this from it (after restart) :
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".
Data page checksums are disabled.
fixing permissions on existing directory /tmp ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Etc/UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
My docker-compose.yml :
version: '3.2'
services:
db:
image: registryodoo.azurecr.io/samples/postgres:13
volumes:
- db:/var/lib/postgresql/data/pgdata
deploy:
restart_policy:
condition: always
ports:
- "5432:5432"
environment:
POSTGRES_PASSWORD: odoo
POSTGRES_DB: postgres
POSTGRES_USER: odoo
PGDATA: /tmp
healthcheck:
test: ["CMD-SHELL", "pg_isready -U odoo"]
interval: 5s
timeout: 5s
retries: 5
odoocontainer:
depends_on:
db:
condition: service_healthy
image: registryodoo.azurecr.io/samples/odoo:latest
volumes:
- data:/var/lib/odoo
- extra-addons:/mnt/extra-addons
ports:
- 8069:8069
deploy:
restart_policy:
condition: always
environment:
HOST: db
USER: odoo
PASSWORD: odoo
volumes:
data:
driver: azure_file
driver_opts:
share_name: datafileshare
storage_account_name: odooaccount1
db:
driver: azure_file
driver_opts:
share_name: dbfileshare
storage_account_name: odooaccount1
extra-addons:
driver: azure_file
driver_opts:
share_name: odoofileshare
storage_account_name: odooaccount1
Can't figure what's the origin issue and how to solve it

Gunicorn as Service not recognizing Python dependencies

I am running a Flask app on a Ubuntu Linode Server using Gunicorn to serve the app and nginx as a reverse proxy.
I have one app running successfully, but I have a second app where I'm running in to the following problem.
What does work
when I run FLASK_APP=tester.py python3 -m flask run
This works, tester.py runs the app bound to 0.0.0.0 on port 5100 and I can access it from my browser.
when I run gunicorn --bind 0.0.0.0:5100 wsgi:app
This also works, as my wsgi.py imports my app object making it accessible for wsgi
Useful details
which python gives me /usr/bin/python
which pip gives /usr/bin/pip and which pip3 gives /usr/bin/pip3
which python3 gives me /usr/bin/python3
which gunicorn gives me /usr/bin/gunicorn
I am not using a virtual environment since boths app have near identical dependencies
What's not working
I created a service for forwarding traffic with nginx with:
/etc/systemd/system/testpad.service
[Unit]
# specifies metadata and dependencies
Description=Gunicorn instance to serve myproject
After=network.target
# tells the init system to only start this after the networking target has been reached
# We will give our regular user account ownership of the process since it owns all of the relevant files
[Service]
# Service specify the user and group under which our process will run.
User=www-data
# give group ownership to the www-data group so that Nginx can communicate easily with the Gunicorn processes.
Group=www-data
# We'll then map out the working directory and set the PATH environmental variable so that the init system knows where our the executabl>
WorkingDirectory=/home/xxx/xxx
# We'll then specify the commanded to start the service
ExecStart=/usr/bin/gunicorn --bind unix:testpad.sock --access-logfile /home/xxx/xxx/accesslog --error-logfile /home/xxx/xxx/errorlog -m 007 wsgi:app
# This will tell systemd what to link this service to if we enable it to start at boot. We want this service to start when the regular m>
[Install]
WantedBy=multi-user.target
when I start the service it runs for a second then I get this from sudo systemctl status testpad
testpad.service - Gunicorn instance to serve myproject
Loaded: loaded (/etc/systemd/system/testpad.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Mon 2021-09-06 15:47:59 UTC; 16min ago
Process: 655575 ExecStart=/usr/bin/gunicorn --bind unix:testpad.sock --access-logfile /home/xxx/xxx/acces>
Main PID: 655575 (code=exited, status=1/FAILURE)
Sep 06 15:47:54 microportalbeta systemd[1]: Started Gunicorn instance to serve myproject.
Sep 06 15:47:59 microportalbeta systemd[1]: testpad.service: Main process exited, code=exited, status=1/FAILURE
Sep 06 15:47:59 microportalbeta systemd[1]: testpad.service: Failed with result 'exit-code'.
so when I cat errorlog I get
[2021-09-06 15:21:31 +0000] [655222] [INFO] Worker exiting (pid: 655222)
[2021-09-06 15:21:31 +0000] [655223] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
worker.init_process()
File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 134, in init_process
self.load_wsgi()
File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
self.wsgi = self.app.wsgi()
File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
return self.load_wsgiapp()
File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
return util.import_app(self.app_uri)
File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 384, in import_app
mod = importlib.import_module(module)
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/xxx/xxx/wsgi.py", line 1, in <module>
from run import app
File "/home/xxx/xxx/run.py", line 1, in <module>
from genedflask import create_app, db
File "/home/xxx/xxx/xxx/__init__.py", line 5, in <module>
from flask_login import LoginManager
ModuleNotFoundError: No module named 'flask_login'
[2021-09-06 15:21:31 +0000] [655223] [INFO] Worker exiting (pid: 655223)
[2021-09-06 15:21:32 +0000] [655220] [WARNING] Worker with pid 655223 was terminated due to signal 15
[2021-09-06 15:21:32 +0000] [655220] [WARNING] Worker with pid 655222 was terminated due to signal 15
[2021-09-06 15:21:32 +0000] [655220] [INFO] Shutting down: Master
[2021-09-06 15:21:32 +0000] [655220] [INFO] Reason: Worker failed to boot.
[2021-09-06 15:23:34 +0000] [655249] [INFO] Starting gunicorn 20.1.0
[2021-09-06 15:23:34 +0000] [655249] [ERROR] Retrying in 1 second.
[2021-09-06 15:23:35 +0000] [655249] [ERROR] Retrying in 1 second.
[2021-09-06 15:23:36 +0000] [655249] [ERROR] Retrying in 1 second.
[2021-09-06 15:23:37 +0000] [655249] [ERROR] Retrying in 1 second.
[2021-09-06 15:23:38 +0000] [655249] [ERROR] Retrying in 1 second.
[2021-09-06 15:23:39 +0000] [655249] [ERROR] Can't connect to testpad.sock
[2021-09-06 15:28:44 +0000] [655315] [INFO] Starting gunicorn 20.1.0
[2021-09-06 15:28:44 +0000] [655315] [ERROR] Retrying in 1 second.
[2021-09-06 15:28:45 +0000] [655315] [ERROR] Retrying in 1 second.
[2021-09-06 15:28:46 +0000] [655315] [ERROR] Retrying in 1 second.
[2021-09-06 15:28:47 +0000] [655315] [ERROR] Retrying in 1 second.
[2021-09-06 15:28:48 +0000] [655315] [ERROR] Retrying in 1 second.
[2021-09-06 15:28:49 +0000] [655315] [ERROR] Can't connect to testpad.sock
[2021-09-06 15:31:09 +0000] [655348] [INFO] Starting gunicorn 20.1.0
[2021-09-06 15:31:09 +0000] [655348] [ERROR] Retrying in 1 second.
[2021-09-06 15:31:10 +0000] [655348] [ERROR] Retrying in 1 second.
[2021-09-06 15:31:11 +0000] [655348] [ERROR] Retrying in 1 second.
[2021-09-06 15:31:12 +0000] [655348] [ERROR] Retrying in 1 second.
[2021-09-06 15:31:13 +0000] [655348] [ERROR] Retrying in 1 second.
[2021-09-06 15:31:14 +0000] [655348] [ERROR] Can't connect to testpad.sock
[2021-09-06 15:33:34 +0000] [655387] [INFO] Starting gunicorn 20.1.0
[2021-09-06 15:33:34 +0000] [655387] [ERROR] Retrying in 1 second.
[2021-09-06 15:33:35 +0000] [655387] [ERROR] Retrying in 1 second.
[2021-09-06 15:33:36 +0000] [655387] [ERROR] Retrying in 1 second.
[2021-09-06 15:33:37 +0000] [655387] [ERROR] Retrying in 1 second.
[2021-09-06 15:33:38 +0000] [655387] [ERROR] Retrying in 1 second.
[2021-09-06 15:33:39 +0000] [655387] [ERROR] Can't connect to testpad.sock
[2021-09-06 15:47:54 +0000] [655575] [INFO] Starting gunicorn 20.1.0
[2021-09-06 15:47:54 +0000] [655575] [ERROR] Retrying in 1 second.
[2021-09-06 15:47:55 +0000] [655575] [ERROR] Retrying in 1 second.
[2021-09-06 15:47:56 +0000] [655575] [ERROR] Retrying in 1 second.
[2021-09-06 15:47:57 +0000] [655575] [ERROR] Retrying in 1 second.
[2021-09-06 15:47:58 +0000] [655575] [ERROR] Retrying in 1 second.
[2021-09-06 15:47:59 +0000] [655575] [ERROR] Can't connect to testpad.sock
Not sure why it is not finding flask-login as it is installed under pip and pip3 globally, and is visible when I run pip3 list or pip list.
I assume that once I overcome this hurdle then the testpad.sock file should auto create as it did with my previous app. Most people with this problem I found it was an issue with gunicorn looking at the global environment when people installed dependencies in a virtual environment, which I am not doing in this circumstance.
Any suggestions?
Update
I never did figure out why it could not find the libraries when ran as a service, I even set the PYTHONPATH variable to see if that would help.
What I did do is give up on running as a service and instead just ran the application as a background process on port 8000 and just directed nginx to forward traffic there, and that worked.

Docker (compose): connection refused without sudo

All was fine until "something". After that "something", I could use docker and docker-compose with sudo but without it the docker would hang indefinitely and the docker-compose would return connection stack traces.
Doesn't work:
Running docker without sudo hangs indefinitely. Temporarily fixed by exporting DOCKER_HOST=tcp://127.0.0.1:2375.
docker-compose without sudo returns with connection refused. It's not about connecting to specific container but for all basic commands such as docker-compose ps.
Proof that user belongs to docker group:
kretyn#junk$ groups kretyn
kretyn : kretyn adm cdrom sudo dip plugdev lpadmin lxd sambashare docker
Solution hints
I had a docker context activated that was pointing at existing but inactive host. Removing that context and unsetting DOCKER_HOST allowed the docker command to work correctly. That's a surprise since I reinstalled (purged everything I could find) the docker before writing this question.
Removing context isn't sufficient. Docker Compose required explicit docker context use default otherwise it wouldn't understand.
The problem with docker-compose ps is still present.
Stack trace on docker-compose
kretyn#junk$ docker-compose ps
Traceback (most recent call last):
File "urllib3/connection.py", line 159, in _new_conn
File "urllib3/util/connection.py", line 84, in create_connection
File "urllib3/util/connection.py", line 74, in create_connection
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "urllib3/connectionpool.py", line 670, in urlopen
File "urllib3/connectionpool.py", line 392, in _make_request
File "http/client.py", line 1255, in request
File "http/client.py", line 1301, in _send_request
File "http/client.py", line 1250, in endheaders
File "http/client.py", line 1010, in _send_output
File "http/client.py", line 950, in send
File "urllib3/connection.py", line 187, in connect
File "urllib3/connection.py", line 171, in _new_conn
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f762c4e3e20>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "requests/adapters.py", line 439, in send
File "urllib3/connectionpool.py", line 726, in urlopen
File "urllib3/util/retry.py", line 446, in increment
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=2375): Max retries exceeded with url: /version (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f762c4e3e20>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "docker/api/client.py", line 214, in _retrieve_server_version
File "docker/api/daemon.py", line 181, in version
File "docker/utils/decorators.py", line 46, in inner
File "docker/api/client.py", line 237, in _get
File "requests/sessions.py", line 543, in get
File "requests/sessions.py", line 530, in request
File "requests/sessions.py", line 643, in send
File "requests/adapters.py", line 516, in send
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=2375): Max retries exceeded with url: /version (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f762c4e3e20>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "docker-compose", line 3, in <module>
File "compose/cli/main.py", line 80, in main
File "compose/cli/main.py", line 189, in perform_command
File "compose/cli/command.py", line 60, in project_from_options
File "compose/cli/command.py", line 152, in get_project
File "compose/cli/docker_client.py", line 41, in get_client
File "compose/cli/docker_client.py", line 170, in docker_client
File "docker/api/client.py", line 197, in __init__
File "docker/api/client.py", line 221, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: HTTPConnectionPool(host='127.0.0.1', port=2375): Max retries exceeded with url: /version (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f762c4e3e20>: Failed to establish a new connection: [Errno 111] Connection refused'))
[46145] Failed to execute script docker-compose
Versions/builds
Linux distro
kretyn#junk$ uname -a
Linux junk 5.8.0-43-generic #49~20.04.1-Ubuntu SMP Fri Feb 5 09:57:56 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
Docker
kretyn#junk$ sudo docker system info
Client:
Context: default
Debug Mode: false
Plugins:
app: Docker App (Docker Inc., v0.9.1-beta3)
buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)
Server:
Containers: 9
Running: 8
Paused: 0
Stopped: 1
Images: 44
Server Version: 20.10.3
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Cgroup Version: 1
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc version: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
init version: de40ad0
Security Options:
apparmor
seccomp
Profile: default
Kernel Version: 5.8.0-43-generic
Operating System: Ubuntu 20.04.2 LTS
OSType: linux
Architecture: x86_64
CPUs: 12
Total Memory: 15.29GiB
Name: meland
ID: 3PE6:4AWU:LGRR:HOBJ:XUCJ:ER4H:ZEF5:MWUJ:COEG:WPK5:YH2U:FKUF
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
WARNING: No blkio weight support
WARNING: No blkio weight_device support
Docker-compose
kretyn#junk$ sudo docker-compose version
docker-compose version 1.28.0, build d02a7b1a
docker-py version: 4.4.1
CPython version: 3.9.0
OpenSSL version: OpenSSL 1.1.1d 10 Sep 2019
The problem was a dead context entry.
Solution
Removed the dead context named remote using docker context rm remote.
Even though docker context ls was pointing default as default, it was necessary to do docker context use default for the context to be properly updated.
As a partial fix I had previously set DOCKER_HOST to tcp://127.0.0.1:2375. After updating context the env variable had to be unset, i.e. unset DOCKER_HOST.
Lazy commands, assuming context remote:
$ docker context rm remote
$ docker context use default
$ unset DOCKER_HOST
Background
Had a remote context that was based on ssh endpoint. My ssh config was set that the name points at my domain but recently the host behind it was removed.
Interestingly, I've been "fixing" this for a while and one of the steps was to completely purge docker from my local Ubuntu host, including apt, /var/lib/docker, /etc/docker and random scripts in ~/.local/. The context, however, wasn't cleaned.
The solution by Dawid was perfect for me.
I wanna mention that even when your sudo docker context ls only shows default context, your docker context ls might show different (and potentially broken) contexts. You wanna delete them.
But the problem is that your docker ps hangs.
So before you try docker rm, you need to override the context by DOCKER_HOST=tcp://127.0.0.1:2375.
As a result, the full solution is
DOCKER_HOST=tcp://127.0.0.1:2375
docker context ls
docker context rm <broken context name>
docker context use <valid context name(maybe default?)>
unset DOCKER_HOST
and then make sure all docker commands work without sudo.
docker ps
You don't have the necessary rights to use docker or docker-compose without sudo, check the documentation.
sudo usermod -aG docker
sudo chmod +x /usr/local/bin/docker-compose
You have to restart your terminal after that.

Getting a 500 Internal Server Error even with fixes as recommended in a couple of similar questions

I'm having same issue as described in these two questions/answers:
Python WSGI + Flask render_template - 500 Internal Server Error?
Getting a 500 Internal Server Error using render_template and Flask
and I've narrowed it to the following:
Here's the file structure:
../project/
project.py
templates/
about.html
I'm still getting this error (shorten):
● project.service - Gunicorn instance to serve project
Loaded: loaded (/etc/systemd/system/project.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2020-02-15 06:28:46 UTC; 3min 28s ago
Main PID: 3942 (gunicorn)
Tasks: 4 (limit: 1151)
CGroup: /system.slice/project.service
├─3942 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
├─3967 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
├─3968 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
└─3969 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
Feb 15 06:29:17 project gunicorn[3942]: return self._load_template(name, self.make_globals(globals))
Feb 15 06:29:17 project gunicorn[3942]: File "/home/dev/project/project_env/lib/python3.6/site-packages/jinja2/environment.py", line 857, in _load_template
Feb 15 06:29:17 project gunicorn[3942]: template = self.loader.load(self, name, globals)
Feb 15 06:29:17 project gunicorn[3942]: File "/home/dev/project/project_env/lib/python3.6/site-packages/jinja2/loaders.py", line 117, in load
Feb 15 06:29:17 project gunicorn[3942]: source, filename, uptodate = self.get_source(environment, name)
Feb 15 06:29:17 project gunicorn[3942]: File "/home/dev/project/project_env/lib/python3.6/site-packages/flask/templating.py", line 60, in get_source
Feb 15 06:29:17 project gunicorn[3942]: return self._get_source_fast(environment, template)
Feb 15 06:29:17 project gunicorn[3942]: File "/home/dev/project/project_env/lib/python3.6/site-packages/flask/templating.py", line 89, in _get_source_fast
Feb 15 06:29:17 project gunicorn[3942]: raise TemplateNotFound(template)
Feb 15 06:29:17 project gunicorn[3942]: jinja2.exceptions.TemplateNotFound: about.html
So the issue as far as I can tell, is that last line
Feb 15 06:29:17 project gunicorn[3942]: jinja2.exceptions.TemplateNotFound: about.html
I don't understand why, even though the files/folders are there. The closest I could find is this comment:
https://stackoverflow.com/a/56589998/12070612
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
But if I add the "ENV=..." lines to my project.py file, then Gunicorn complaints and fails to start process.
There are different ways in Flask to render HTML. You could simply generate that HTML directly from the Python code similar to what you have done for the home route or you could use a templating language like Jinja.
What you have written in the about route is the render_template function. The way render_template works is by reading an HTML file with the name you pass as a parameter and renders that template. In you case, you have called the render_template method and asked it to render a template called about.html but since the template does not exist, it fails to load and throws an exception.
Create an about.html file at the same level as your app.py file and type in something in it and try to render. It should work.
To read more on render_template check out the documentation here or read the getting started tutorial for Flask here

ModuleNotFoundError: No module named 'hello' when called from Dockerfile

I am trying to read the module hello.py from Dockerfile and seeing the below error:
ModuleNotFoundError: No module named 'hello'
I have tried changing the directory to the current working directory where hello.py is present, but that still doesn't help.
The tree structure as below with hello.py and Dockerfile at the same location:
├── Dockerfile
├── hello.py
├── __init__.py
├── Procfile
├── README.txt
├── requirements.txt
Dockerfile content:
FROM python:3.6.7
RUN pip install gunicorn
EXPOSE 5000
CMD PYTHONPATH=`pwd`/.. gunicorn --bind 0.0.0.0:5000 hello:app
Output when running the container
-----> docker run -p 5000:5000 <image_name>
[2019-06-29 05:03:02 +0000] [7] [INFO] Starting gunicorn 19.9.0
[2019-06-29 05:03:02 +0000] [7] [INFO] Listening at: http://0.0.0.0:5000 (7)
[2019-06-29 05:03:02 +0000] [7] [INFO] Using worker: sync
[2019-06-29 05:03:02 +0000] [10] [INFO] Booting worker with pid: 10
[2019-06-29 05:03:02 +0000] [10] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()
File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
self.load_wsgi()
File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
self.wsgi = self.app.wsgi()
File "/usr/local/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
return self.load_wsgiapp()
File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
return util.import_app(self.app_uri)
File "/usr/local/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
__import__(module)
ModuleNotFoundError: No module named 'hello'
[2019-06-29 05:03:02 +0000] [10] [INFO] Worker exiting (pid: 10)
[2019-06-29 05:03:02 +0000] [7] [INFO] Shutting down: Master
[2019-06-29 05:03:02 +0000] [7] [INFO] Reason: Worker failed to boot.
What am i missing the Dockerfile?
you are missing the COPY line:
FROM python:3.6.7
RUN pip install gunicorn
COPY . . #copy everything in the context to the current dir in the container
EXPOSE 5000
CMD PYTHONPATH=`pwd`/.. gunicorn --bind 0.0.0.0:5000 hello:app
otherwise the container would not include your files

Resources