首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Postgres数据库未连接到烧瓶应用程序(连接到"localhost“的服务器(127.0.0.1),端口5432失败)

Postgres数据库未连接到烧瓶应用程序(连接到"localhost“的服务器(127.0.0.1),端口5432失败)
EN

Stack Overflow用户
提问于 2022-02-15 14:20:20
回答 1查看 720关注 0票数 -1

我正在使用postgres数据库进行一个烧瓶/角度项目。当我运行我的docker-conpose.yml时,后端会停止并显示此错误。

连接到服务器的"localhost“(127.0.0.1),端口5432失败:连接被拒绝,服务器是否在该主机上运行并接受TCP/IP连接?

虽然当我在TablePlus上测试使用docker-compose.yml TablePlus中的URL连接到数据库时,我还是可以连接。

这是我的船坞-Compose.yml

代码语言:javascript
复制
version: '3.9'

services:
  #Backend build
  api:
    build: ./Backend
    depends_on:
      - database
    ports:
      - 5000:5000
    expose: 
      - "5432"
    environment:
      Stage: development
      DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/onlineexam-database-1
      SQLALCHEMY_DATABASE_URI: postgresql+psycopg2://postgres:postgres@database/
    volumes:
        - .:/code

  #Frontend Build
  web:
    build: ./frontend
    image: frontend
    container_name: frontend
    restart: always
    environment:
        PORT: 4200
        PROXY_API: http://quizme:5000/
        API_URL: 'http://localhost:5000'
    ports:
    - "4200:80"
   # expose: 
  #  - "4200"
    
  #DB build
  database:
    
    environment: 
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: onlineexam-database-1
    image: 'postgres:latest'
    restart: always
    ports:
      - 5432:5432
    volumes:
      - ./db-data/:/var/lib/postgresql/data=rwx/

这是我的app.py。entities.entity.Base.metadata.create_all(entities.entity.engine)命令是发生错误的地方。

代码语言:javascript
复制
# creating the Flask application
app = Flask(__name__)


CORS(app)


oauth = OAuth(app)

# if needed, generate database schema
entities.entity.Base.metadata.create_all(entities.entity.engine)

auth0 = oauth.register(
    'auth0',
    client_id='kYsfByzSV4rxmTJSX6jmaQumLeJZVjoM',
    client_secret='fDR6hxNSGJApKrxTdZyD2EC4ezV6oV4F5AlM_lm_Pvgb8UijifazIeJ8b3HzBEUL',
    api_base_url='https://dev-4-frsuj0.us.auth0.com',
    access_token_url='https://dev-4-frsuj0.us.auth0.com/oauth/token',
    authorize_url='https://dev-4-frsuj0.us.auth0.com/authorize',
    client_kwargs={
        'scope': 'Manage exams',
    },
)

# Routes for login, callback 
@app.route('/login')
def login():
    return auth0.authorize_redirect(redirect_uri='http://localhost:5000')

@app.route('/callback')
def callback_handling():
    # Handles response from token endpoint
    auth0.authorize_access_token()
    resp = auth0.get('userinfo')
    userinfo = resp.json()

    # Store the user information in flask session.
    session['jwt_payload'] = userinfo
    session['profile'] = {
        'user_id': userinfo['sub'],
        'name': userinfo['name'],
        'picture': userinfo['picture']
    }
    return redirect('/dashboard')

@app.route('/exams')
def get_exams():
    # fetching from the database
    session = entities.entity.Session()
    exam_objects = session.query(entities.exam.Exam).all()

    # transforming into JSON-serializable objects
    schema = entities.exam.ExamSchema(many=True)
    exams = schema.dump(exam_objects)

    # serializing as JSON
    session.close()
    return jsonify(exams)


@app.route('/exams', methods=['POST'])
@auth.requires_auth
def add_exam():
    # mount exam object
    posted_exam = entities.exam.ExamSchema(only=('title', 'description'))\
        .load(request.get_json())

    exam = entities.exam.Exam(**posted_exam, created_by="HTTP post request")

    # persist exam
    session = entities.entity.Session()
    session.add(exam)
    session.commit()

    # return created exam
    new_exam = entities.exam.ExamSchema().dump(exam).data
    session.close()
    return jsonify(new_exam), 201

@app.errorhandler(auth.AuthError)
def handle_auth_error(ex):
    response = jsonify(ex.error)
    response.status_code = ex.status_code
    return response

我的entity.py。这就是我创建引擎并绑定它的地方。

代码语言:javascript
复制
# coding=utf-8

from datetime import datetime
from sqlalchemy import create_engine, Column, String, Integer, DateTime,Table,MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


#Database variables
db_url = 'localhost:5432'
db_name = 'onlineexam-database-1'
db_user = 'postgres'
db_password = 'postgres'

#Connect to database through sqlalchemy
engine = create_engine(f'postgresql://{db_user}:{db_password}@{db_url}/{db_name}')
Session = sessionmaker(bind=engine)

Base = declarative_base()


class Entity():
    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    last_updated_by = Column(String)

    def __init__(self, created_by):
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
        self.last_updated_by = created_by

config.py和env.dev

代码语言:javascript
复制
import os


basedir = os.path.abspath(os.path.dirname(__file__))


class Config(object):
    SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL", "sqlite://")
    SQLALCHEMY_TRACK_MODIFICATIONS = False

FLASK_ENV=development
FLASK_APP=src:app.py
DATABASE_URL=postgresql://online_exam:online_exam@db:5432/online_exam_dev

nginx/conf

代码语言:javascript
复制
server {
    listen       80;
    server_name  localhost;
    location / {
        proxy_pass   http://app:8000;
    }
    location /hit {
        proxy_pass   http://app:8000/visitor;
    }
    location /hit/reset {
        proxy_pass   http://app:8000/visitor/reset;
    }
}

Dockerfile

代码语言:javascript
复制
FROM nginx:1.13
COPY conf /etc/nginx/conf.d/default.conf
FROM python:3.9-slim-buster
ENV FLASK_APP=/backend/src/app/__init__.py
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY . .

RUN pip3 install -r requirements.txt
RUN pip3 install requests
RUN pip3 install pipenv
RUN pip3 install psycopg2-binary
RUN pipenv install sqlalchemy psycopg2-binary

EXPOSE 5000
WORKDIR /src

ENTRYPOINT [ "python" ]

CMD [ "app.py" ]
EN

回答 1

Stack Overflow用户

发布于 2022-02-15 20:48:44

当从其他容器中访问容器时,请使用停靠者-组合服务名称.在你的例子中是database

所以试试这个网址:

postgresql://postgres:postgres@database:5432/onlineexam-database-1

请参阅:https://docs.docker.com/compose/networking/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71128069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档