0

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)

1 Answers1

0

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.

Ian Wilson
  • 6,223
  • 1
  • 16
  • 24