无法从停靠的Django连接到外部PostgreSQL数据库

wz1wpwve  于 2022-10-04  发布在  Go
关注(0)|答案(1)|浏览(183)

我正在运行停靠的Django应用程序,并试图连接到位于具有公共IP的外部主机的PostgreSQL数据库。

运行容器时,makemigrations命令出现以下错误:

  1. django.db.utils.OperationalError: could not connect to server: Connection refused
  2. Is the server running on host "myhost" (89.xx.xx.102) and accepting
  3. TCP/IP connections on port 5432?

但是,在未停靠时,它会成功连接。

下面是docker-compose.yml

  1. services:
  2. backend:
  3. build: .
  4. ports:
  5. - 65534:65534

和对应的Dockerfile

  1. FROM python:3.10 AS builder
  2. ENV PYTHONDONTWRITEBYTECODE=1
  3. ENV PYTHONUNBUFFERED=1
  4. COPY requirements.txt /app/
  5. RUN pip install -r /app/requirements.txt
  6. RUN pip install gunicorn
  7. FROM builder
  8. COPY ./ /app/
  9. ENTRYPOINT [ "/app/entrypoint.sh" ]

entrypoint.sh

  1. # !/bin/bash
  2. python /app/manage.py collectstatic --no-input --clear
  3. python /app/manage.py makemigrations
  4. python /app/manage.py migrate --no-input
  5. gunicorn --pythonpath /app/ -b 0.0.0.0:65534 app.wsgi:application

如何使Django应用程序能够连接到外部托管的PostgresSQL数据库?

nwo49xxi

nwo49xxi1#

在您的终端中运行以下命令:

  1. vim /etc/postgresql/14/main/postgresql.conf #14 is the version of postgres.

取消注解并编辑Listen_Addresses属性以开始侦听,以开始侦听所有可用IP地址。

  1. listen_addresses = '*'

在文件底部追加一个新的连接策略(一个模式代表[CONNECTION_TYPE][DATABASE][USER][ADDRESS][METHOD])。

  1. host all all 0.0.0.0/0 md5

我们允许具有任何IPv4地址(0.0.0.0/0)的所有用户(ALL)使用MD5加密密码进行身份验证(MD5),将(主机)连接到所有数据库(ALL)。

现在可以重新启动您的PostgreSQL服务以加载您的配置更改。

  1. systemctl restart postgresql

并确保您的系统正在侦听为PostgreSQL保留的5432端口。

  1. ss -nlt | grep 5432

通过远程主机连接到PostgreSQL数据库:

您的PostgreSQL服务器现在正在运行并侦听外部请求。现在可以通过远程主机连接到数据库了。

命令行工具连接:

现在,您可以使用以下命令模式连接到远程数据库:

  1. psql -h [ip address] -p [port] -d [database] -U [username]

现在,让我们连接到我们托管的远程PostgreSQL数据库。

  1. psql -h 5.199.162.56 -p 5432 -d test_erp -U postgres

要仔细检查您的连接详细信息,请使用**\Conninfo**命令。

展开查看全部

相关问题