trying to connect two docker containers postgres and flask webapp [duplicate] - postgresql

This question already has answers here:
How to communicate between Docker containers via "hostname"
(5 answers)
Closed 3 months ago.
i have two containers flask webapp and postgres so want to connect them without using the Docker-compose
FLASK APP CODE
from flask import Flask, render_template, request,current_app
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:password#localhost:5433/students'
db=SQLAlchemy(app)
class Student(db.Model):
__tablename__='students'
id=db.Column(db.Integer,primary_key=True)
fname=db.Column(db.String(40))
lname=db.Column(db.String(40))
pet=db.Column(db.String(40))
def __init__(self,fname,lname,pet):
self.fname=fname
self.lname=lname
self.pet=pet
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
fname= request.form['fname']
lname=request.form['lname']
pet=request.form['pets']
student=Student(fname,lname,pet)
db.session.add(student)
db.session.commit()
return render_template('success.html', data=fname)
if __name__ == '__main__': #python interpreter assigns "__main__" to the file you run
with app.app_context():
db.create_all()
app.run(host='0.0.0.0',debug=True)
sudo docker run --name some-postgres -e POSTGRES_PASSWORD=password --rm -p 5433:5432 postgres
this is how i ran the postgres
this is how is the Docker file
FROM ubuntu
RUN apt update -y
RUN apt upgrade -y
RUN apt install python3 -y
RUN apt-get install python3-pip -y
RUN apt-get install python3-dev -y
RUN pip3 install flask
RUN python3 -m pip install psycopg2-binary
RUN pip3 install flask-sqlalchemy
COPY . .
CMD ["python3","app.py"]
this is the how i ran the web app
sudo docker run -p 5000:5000 trial:1
return self.dbapi.connect(*cargs, **cparams) File "/usr/local/lib/python3.10/dist-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5433? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5433?
(Background on this error at: https://sqlalche.me/e/14/e3q8)

Docker networking has been difficult for me. I think you can do this for the app container:
sudo docker run --network="host" trial:1
The port mapping doesn't work anymore because you are sharing your network with your host machine.
If you put the two containers on a network created via docker network create then you can give the containers names and connect to them that way. And you don't have to expose the postgres port to the host. But that all starts to add up and is why I had to use docker-compose.

Related

How do i install Postgres on Ubuntu and create a superuser?

I have successfully installed Postgres on Ubuntu 20.04 by running the following commands:
$ sudo apt-get update
$ sudo apt-get install postgresql postgresql-contrib libpq-dev
which was successful. I then run the command:
$ sudo service postgresql start
which was also successful.
However, the command
$ sudo -u postgres createdb $USER
failed. The error message was as follows:
createuser: error: could not connect to database template1: 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"?
Please help me out.

docker container can not connect to local postgres [duplicate]

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(40 answers)
Closed 2 years ago.
Can't connect to Postgres from the docker container.
I do not want user docker-compose and create a Postgres container, already got Postgres app running. I think it is a bad idea to container postgres and better use system.
OSX, Postgres10, Flask
I already made
postgresql.conf
listen_addresses = '*'
port = 5432
pg_hba.conf
host all all 0.0.0.0/0 trust
I Used trust for any result, but no effect.
Dockerfile
FROM python:3.8-alpine
RUN apk update \
&& apk add --virtual build-deps gcc musl-dev \
&& apk add python3-dev \
&& apk add postgresql-dev \
&& apk add jpeg-dev zlib-dev libjpeg \
&& pip install --upgrade pip
ENV PYTHONUNBUFFERED 1 \
&& FLASK_APP app.py
#EXPOSE 5000 5432
WORKDIR /app
ADD . /app
RUN pip install -r requirements.txt
CMD ["./bin/run.sh"]
./bin/run.sh
#!/bin/sh
#python run.py
source venv/bin/activate
set -e
flask db upgrade
exec gunicorn -b --workers 4 --access-logfile --error-logfile run:app :5000
The "docker run" command I try to use:
docker run --rm -e SQLALCHEMY_DATABASE_URI=postgresql://postgres:postgres#0.0.0.0:5432/my_db --net=host -p 5000:5000 my_container:v0.1
the command leads to error
...
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "0.0.0.0" and accepting
TCP/IP connections on port 5432?
command connect me to Postgres
psql -U postgres -h 0.0.0.0
Trying to connect to host "0.0.0.0" is technically wrong. (the address 0.0.0.0 is used to other purposes no to connect to...)
Did you tried connect using the postgres container ip address instead of "0.0.0.0"?
You can get the postgres container ip address throught the following command:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' name_of_postgres_container

could not connect to database postgres

createuser: could not connect to database postgres: 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 trying to install dspace 6.3 on ubuntu server 18.04 but after installing postgresql when I run the command createuser -U postgres -d -A -P dspace I am getting the above error help please
Did you start the server? Try sudo service postgresql restart or sudo systemctl restart postgresql

Docker container connecting to Postgres database

I am receiving the following error when connecting my Django docker container to my Postgres database.
File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line
130, in connect conn = _connect(dsn,
connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not connect to server:
Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
Below is my Dockerfile which run the container
FROM python:3.6
MAINTAINER c15523957
RUN apt-get -y update
RUN apt-get -y upgrade
RUN apt-get -y install libgdal-dev
RUN mkdir -p /usr/src/app
COPY requirements.txt /usr/src/app/
COPY . /usr/src/app
WORKDIR /usr/src/app
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Here is the code in my settings.py file of my Django code
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'place_loc_db',
'USER': 'place_loc_user',
'PASSWORD': 'abc123',
'HOST': 'localhost',
'PORT': 5432,
}
}
Note: I do not have the postgres database running as a container but on my local computer
Note: The following details are contained in my pg_hba.conf and postgresql.conf files
postgresql.conf- > listen_addresses = '*'
pg_hba.conf - > host all all 0.0.0.0/0 md5
I've read that the following details above open connections on the database.
It looks like you're trying to connect to localhost. Your Postgres database is notrunning inside the same container as your django app, so you're not going to be able to find it at localhost. You need to point your app at the address of the Postgres container.
If you run your containers in a user defined network (using docker-compose will do this for you automatically), then you can use container name as hostnames.
The documentation on container networking is a good place to start.
Update
The fact that you're running Postgres on your host doesn't substantially change the answer: you still need to point your webapp at the address of the Postgres server, rather than localhost.
The easiest way of doing that depends on whether or not you're running Docker natively on Linux, or you're running Docker-For-X, where X is MacOS or Windows.
On Linux, just point your webapp at the ip address of the docker0 interface. This is an address of your host, and since you have Postgres configured to listen on all interfaces, this should work out just fine.
If you're on Mac or Windows, there is a special "magic hostname" that refers to services on your host. E.g., read this for details under MacOS. In both cases, you can point your webapp at host.docker.internal.
Make sure this is done
postgresql.conf- > listen_addresses = '*'
pg_hba.conf - > host all all 0.0.0.0/0 md5
brew services start postgresql (In MAC, reload postgres Service ).
Get your system Ip.
Use your system ip address instead of localhost in your DB connection.

connect to postgres container from flask app inside container

I have my flask app app.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
APP = Flask(__name__)
DB = SQLAlchemy()
if __name__ == '__main__':
APP.config.from_mapping(
SQLALCHEMY_DATABASE_URI='postgres://postgres:password#0.0.0.0:5432',
SQLALCHEMY_TRACK_MODIFICATIONS=False
)
DB.init_app(APP)
DB.create_all(app=APP)
APP.run(use_reloader=False, host='0.0.0.0', port='5000')
and I have a Dockerfile for it:
FROM python:3.6-alpine
RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev
WORKDIR /root
COPY app.py .
RUN pip3 install Flask==1.0.2
RUN pip3 install psycopg2-binary==2.7.6.1
RUN pip3 install Flask-SQLAlchemy==2.3.2
CMD ["python3", "app.py"]
I run:
docker build . --tag flaskapp:1
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password --name database postgres
docker run --rm -p 5000:5000 flaskapp:1
I then get an exception which points out:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "0.0.0.0" and accepting
TCP/IP connections on port 5432?
How do I fix this?
You have specified 0.0.0.0 as the IP address to connect to, which doesn't make sense. 0.0.0.0 is the "Any Address". You probably saw a message that postgres was listening on 0.0.0.0, which is where you got it from. In the context of a server listening on 0.0.0.0, it means that it is listening on all ipv4 interfaces. See https://en.wikipedia.org/wiki/0.0.0.0 for more information about the special 0.0.0.0 address and what it means.
If you want to connect to the postgres service, then you would need to use a valid ip address or dns name of where it is running.
In Docker, if you have multiple named containers connected to the same user-defined network, you can make use of the built-in service discovery mechanism that Docker ships with.
Here's a modified set of commands to run to take advantage of this:
docker network create mynet
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password --net mynet --name database postgres
docker run --rm -p 5000:5000 --net mynet flaskapp:1
Be sure to change your code to connect to postgres://postgres:password#database:5432 instead of postgres://postgres:password#0.0.0.0:5432