简体   繁体   中英

I have a django app in a ubuntu virtual machine and can't remotely access the postgres database

I deployed an application in django on GCP in a VM (ubuntu 22.04 01 LTS)

The app is working normally, database is postgresql.

But I can't remotely access the database, I always get timeout error.

My settings.py

....
DATABASES = {
    'default': {
        'ENGINE': os.environ.get('DATABASE_ENGINE'),
        'NAME': os.environ.get('DATABASE_NAME'),
        'USER': os.environ.get('DATABASE_USER'),
        'PASSWORD': os.environ.get('DATABASE_PASSWORD'),
        'HOST': os.environ.get('DATABASE_HOST'),
        'PORT': os.environ.get('DATABASE_PORT'),
    }
}
...

My .env file:

# Postgres
DATABASE_ENGINE = 'django.db.backends.postgresql'
DATABASE_NAME = "basededados"
DATABASE_USER = "user"
DATABASE_PASSWORD = "senha"
DATABASE_HOST = "127.0.0.1"
DATABASE_PORT = "5432"

I created the database like this:

sudo -u postgres psql

CREATE ROLE user WITH LOGIN SUPERUSER CREATEDB CREATEROLE PASSWORD 'senha';

CREATE DATABASE basededados WITH OWNER user;

GRANT ALL PRIVILEGES ON DATABASE basededados TO user;

I already set up the postgres.conf file:

listen_addresses = '*'

And the pg_hba.conf file**:**

# IPv4 local connections:
host    all             all             0.0.0.0/0            md5

I alredy allowed port 5432 through the firewall by executing:

sudo ufw allow 5432/tcp

I'm trying to access the DB like this:

psql -h {Virtual machine IP} -d basededados -U user

the error:

psql: error: connection to server at {Virtual machine IP}, port 5432 failed: Connection timed out
        Is the server running on that host and accepting TCP/IP connections?

Am I doing something wrong?

.env
# Postgres
DATABASE_ENGINE=django.db.backends.postgresql
DATABASE_NAME=basededados
DATABASE_USER=user
DATABASE_PASSWORD=senha
DATABASE_HOST=127.0.0.1
DATABASE_PORT=5432

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM