python 当我启动Docker容器时,我得到了psycopg.OperationalError,带有flask和PostgreSQL

nkkqxpd9  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(107)

我正在使用flask和PostgreSQL数据库构建一个flask RESTful API,并尝试使用docker-compose和Dockerfile停靠应用程序,但当我尝试运行容器时,出现此错误
第一个月

    • 应用程序文件try_flask. py**
from flask import Flask, request, json, jsonify
import psycopg 

app = Flask(__name__)

conn=psycopg.connect("dbname=testing user=postgres port=5432 password=postgres")

cur=conn.cursor()


@app.route('/business_table/',methods=['POST','GET'])
def insert_locations():
    if request.method=="POST":
        business_name=request.form["name"]
        category=request.form["category"]
        cur.execute("select exists(select name from public.business where name=%s)", (business_name,))
        row = cur.fetchone()[0]               
        if row ==False:
            cur.execute("INSERT INTO business(name,category) VALUES(%s, %s) RETURNING business_id ",
            (business_name,category))
            row = cur.fetchone()[0] 
        else:
            return "already exists on the database"
      
        conn.commit()
                
        return f"business with {business_name} is added with id {row}"
    
    elif request.method=="GET":
        cur.execute("SELECT * FROM business")
    
        business=[
                dict(business_id=row[0],name=row[1],category=row[2])
                for row in cur.fetchall()
            ]
        conn.commit()

        return jsonify(business)


if __name__ == "__main__":
    app.run(debug=True,host="0.0.0.0", port=5000)
    • 停靠-编写. yaml文件**
version: '3'
services:
  postgres:
    restart: always
    image: postgis/postgis:15-3.3-alpine
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=testing
    volumes:
      - ./postgres-data/postgres:/var/lib/postgresql/data
    ports:
      - "5432:5432"
  app:
    restart: always
    build: .
    ports:
      - 5000:5000
    volumes: 
      - .:/app
    depends_on:
      - postgres
    entrypoint: ["python", "try_flask.py","runserver"]
    • 停靠文件**
FROM python:3.9.5-slim-buster
RUN apt-get update && apt-get -y install libpq-dev gcc && pip install psycopg
RUN mkdir /app
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5000

PostgreSQL容器运行正常,但问题出在Python容器上,我试过使用这些文件,但总是出现相同的错误,似乎是连接问题,请提供任何解决方案?

db2dz4w8

db2dz4w81#

当您建立数据库连接时,您需要指定Postgres容器的主机名,否则,它将默认为localhost
由于您使用的是Docker Compose,因此Docker创建的网络中的主机名就是服务的名称,在您的示例中就是postgres
参见https://docs.docker.com/compose/networking/

相关问题