Docker: Django & Postgres > How to connect - django

I followed this tutorial here to setup Docker with Django. It works perfectly now and also my Postgres database seems to be installed. Where it fails for me is connecting with Postico (macOS) to my Postgres that's running in the container. Anyone who has experience in that, is it possible to connect 'from the outside' with eg. Postico to this container?
Currently I typed in:
Host localhost
User postgres
Password postgres
But I am not sure about the password, as in the tutorial I never set any.
docker-compose:
version: '3'
services:
db:
image: postgres
web:
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
settings.py
"""
Django settings for composeexample project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XYZ'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'composeexample.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'composeexample.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'

You said in comments:
I actually want to connect from my localhost, but not via terminal, but via Postico as I can easier edit database entries there.
If you wish to connect from localhost, you must expose the ports for pgsql.
version: '3'
services:
db:
image: postgres
expose:
- "5432"
ports:
- "5432:5432"
If you're on Linux, then you have to get your db IP with docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id and connect through the IP.
On Mac you can use localhost to access it.

Related

You're accessing the development server over HTTPS, but it only supports HTTP. code 400, message Bad request syntax

I just started learning Django framework, and I tried to deploy my first project on the server from DigitalOcean. If I run
python3 manage.py runserver 0.0.0.0:8000
The server launches. However, once I try to access it from (my-rent-ip):8000 I get this:
[25/Aug/2021 01:49:01] code 400, message Bad request syntax ('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03GÛî}ز\x921\x0e\x94\x17\x9cÏe¹\x88ñÿÃ\x16\x01éÖRÝ\x00\x95F\x8aG\tÉ 8¯,úÂ\x93´ù\x06Ý\x14¾z\x13Âe4[\x9a,.æ\x96+$<~\x8eq<´\t\x00"ZZ\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00')
[25/Aug/2021 01:49:01] You're accessing the development server over HTTPS, but it only supports HTTP
How is this possible if I run production server, not a development one?
I might be doing something wrong with the setting.py since it had to be changed a lot for the production purposes. I made a production branch, changed settings.py file, and cloned to the server using GitHub. Here it is:
from pathlib import Path
from dotenv import load_dotenv #for python-dotenv method
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
import os
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Thank you so much!
Your server does not support https, so set these settings:
SECURE_SSL_REDIRECT=False
SESSION_COOKIE_SECURE=False
CSRF_COOKIE_SECURE=False
Probably now you need to clear the caches of your browser and restart your server.
The error message refers to the development server because python3 manage.py runserver is used only in development.
Note that you should set up https in your production server (when you will have set up https sets again settings that we changed earlier to True) and that setting ALLOWED_HOSTS = ['*'] is a security issue.
Use http instead of https in url
I had the same problem I was able to access it using http on ec2 ubuntu 20.04
In settings.py use ALLOWED_HOSTS = ['*' ,'18.11.22.58']
Make sure you change ec2 security group and allow traffic to port 8000
Run server like this python3 manage.py runserver 0.0.0.0:8000
Try accesing your site as http://18.11.22.58:8000/ (Not https)
To see how to run on https see here : https://stackoverflow.com/a/51384868/3904109

django not switching to Postres when deploying to Heroku

I deployed my django app with Heroku and I am having troubles with connecting to Postgres.
If I run python manage.py createsuperuser after running heroku ps:exec --app produceit (so I am inside the Heroku instance's terminal), it says that I successfully created a superuser but nothing is written into Heroku Postgress DB...so I can't login into neither /admin nor my app.
I therefore run
heroku ps:exec --app produceit
python manage.py shell
from mywebsite.settings import DATABASES
and it seems like the settings.py has the variable DATABASE still connected to sqlite (see pic)
Funny enough, if I hardcode an admin into Heroku's Postgres DB, loging and then create an instance of one of my models from the app itself (like I create a blog's post)...it actually writes into Postgres and I see it on the Front End.
So basically it's like the app is working on Postgress BUT the terminal is running on SQLite.
What can I do? My settings are below
"""
Django settings for mywebsite project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'action.apps.ActionConfig',
'django_extensions',
'bootstrap_modal_forms',
'widget_tweaks',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#'whitenoise.middleware.WhiteNoiseMiddleware'
]
ROOT_URLCONF = 'mywebsite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mywebsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql',
# 'NAME': '',
# 'HOST': '',
# 'PORT': 5432,
# 'USER': '',
# 'PASSWORD': '',
# }
# }
# Parse database configuration from $DATABASE_URL
#import dj_database_url
#db_from_env = dj_database_url.config(conn_max_age=500)
#DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
#DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
import django_on_heroku
django_on_heroku.settings(locals())
#SECURE_SSL_REDIRECT=True
#SESSION_COOKIE_SECURE=True
#CSRF_COOKIE_SECURE=True
#SECURE_HSTS_SECONDS = 31536000
#SECURE_HSTS_INCLUDE_SUBDOMAINS=True
#SECURE_HSTS_PRELOAD=True
#import django_heroku
#django_heroku.settings(locals())
To get the correct environment variables etc., connect to the terminal via the Heroku dashboard and try it again. You can find it in "More" > "Run Console" > Type in "Bash" on your Heroku-app.

I can't seem to find a way to write into heroku's postgres from my django app

I wrote an app with Django and it has been working fine when running locally. I know deployed it with Heroku and the app run as well.
However, I when I python manage.py createsuperuser it says that I successfully created the superuser but nothing is written into Heroku Postgress DB...so I can login into neither /admin nor my app.
I have been trying debugging like crazy but I can't find the issue. Especially because if I query the DB from django Shell I do see my account, but if I check the Postgress DB of Heroku I don't.
I also checked what DB my python shell is connected to and it seems that it's sqlite, not postgres.
How do I change it so that it connects to postgres?
Also, why is it connected to Sqlite on my shell but if I try to loging on adming it checks if my user extist on postgres?
This is my settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ...
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
#DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'action.apps.ActionConfig',
'django_extensions',
'bootstrap_modal_forms',
'widget_tweaks',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mywebsite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mywebsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Parse database configuration from $DATABASE_URL
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
#DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#import django_on_heroku
#django_on_heroku.settings(locals())
import django_heroku
django_heroku.settings(locals())
Okay, so I've had this very issue so many times when I was trying to upload my website to Heroku. It worked for me the last time when I did something like this:
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '...',
'HOST': '...',
'PORT': 5432,
'USER': '...',
'PASSWORD': '...',
The name, host, user and password can all be found when you create a postresql add on in Heroku itself. You will probably already have a postres add on as default. If not you can add it yourself. You may want to search for YouTube videos, as I found this all from there. I'm not able to remember which one, but if I do, I will link it here.
When you go to your app in Heroku, go to settings and click reveal config vars. Copy the link of the db and paste it somewhere so you can use it as reference. It will be something like this.
postgres://USER:PASSWORD#HOST:PORT/NAME
It sounds like you may be creating a superuser on your local instance rather than on the version on Heroku. Give this a try to create a Django superuser on your Heroku hosted site.
heroku run python manage.py createsuperuser

Why am I getting pymongo ServerSelectionTimeoutError?

This is a small Django project using MongoDB as a database running with Docker. I am getting a pymongo ServerSelectionTimeoutError.
docker-compose.yml
I tried finding the solution with mongo shell using docker exec -it container_id bash but everthing seems fine in there. Command I use to start mongo shell inside a running container is mongo -u signals -p insecure
I also tried to connect to this database using MongoDB Compass and it worked. I am able to connect to MongoDB Compass. Connection string is mongodb://signals:insecure#localhost:27017/webform. I am able to see all the collections in MongoDB Compass but my Django application is not able to connect with database.
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'kv2ischvghz-st=13_-=1d=8ffpjsb_pi*9n%agi)k8w*g+70)'
DEBUG = True
ALLOWED_HOSTS = ['*']
APPEND_SLASH=False
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'WebForm.signals',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'WebForm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'WebForm.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default' : {
'ENGINE': 'djongo',
'ENFORCE_SCHEMA': True,
'NAME': 'webform',
'HOST': 'mongodb',
'PORT': 27017,
'USER': 'signals',
'PASSWORD': 'insecure',
'AUTH_SOURCE': 'admin',
'AUTH_MECHANISM': 'SCRAM-SHA-1',
}
}
CORS_ORIGIN_ALLOW_ALL = True
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'nl-NL'
TIME_ZONE = 'Europe/Amsterdam'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATETIME_FORMAT = 'l d-m-Y, H:i' # e.g. "Donderdag 06-09-2018, 13:56"
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/signals/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
settings.py
In settings.py file, I also tried different host name 'localhost', '127.0.0.1' but still get same error again and again.
I am not able to understand the problem here docker containers are running fine, also able to connect to db using shell and mongodb compass but not my django application. Please help.
Let me know if any more information is needed. Thanks
I solved it. The issue is in the connection string host should be mongo not localhost mongodb://signals:insecure#mongo:27017/webform. Also changed my database image name to mongo.

Not able to connect to postgresql in production, using AWS RDS

my django app, when I ran it locally(localhost + sqlite3) or in production(public Postgres RDS) on port 8000, it works perfectly.
As ports below 1024 are not accessible without root permissions, hence to run on port 80 I used:
sudo python3 manage.py runserver
and got the following error :
OperationalError at /
could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
I am using it from the same region EC2 instance. I was able to make migrations and migrate it over the same RDS Postgres database.
I also tried running on port 80 with gunicorn and root privileges but the same error.
Here is my production settings.py file :
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SKEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main_skeleton',
'storages'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates',],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# SMTP CONFIG
EMAIL_BACKEND = os.environ.get('EMAIL_BACKEND')
EMAIL_HOST = os.environ.get('EMAIL_HOST')
EMAIL_USE_TLS = os.environ.get('EMAIL_USE_TLS')
EMAIL_PORT = os.environ.get('EMAIL_PORT')
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
STATIC_URL = '/static/'
ALLOWED_HOSTS = [os.environ.get('HOST_DOMAIN'), os.environ.get('HOST_IP')]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'HOST': os.environ.get('DB_HOST'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'PORT': os.environ.get('DB_PORT'),
}
}
I checked that I am able to get values from env variables as well.
Your environment variables are not set inside sudo environment
If you want to preserve environment you can use -E
man sudo
The -E (preserve environment) option indicates to the security policy
that the user wishes to preserve their existing environment variables.
The security policy may return an error if the -E option is specified
and the user does not have permission to preserve the environment.
Error you are facing is clearly pointing to this ( from django docs)
If you’re using PostgreSQL, by default (empty HOST), the connection to
the database is done through UNIX domain sockets