docker-django-example icon indicating copy to clipboard operation
docker-django-example copied to clipboard

`./run psql`: connect to specified database

Open kennyhei opened this issue 7 months ago • 6 comments

./run psql command now connects to database that has been set in .env. By default the postgres image uses POSTGRES_USER as db name if POSTGRES_DB is not specified and likewise psql -U [user_name] connects to database [user_name] if database has not been specified with -d flag.

This fixes the issue where username and database name differ.

Note that if POSTGRES_DB is commented out / does not exist in .env, then the script works the old way (psql -U [user_name]).

kennyhei avatar Jun 11 '25 19:06 kennyhei

Hi,

Note that if POSTGRES_DB is commented out / does not exist in .env, then the script works the old way (psql -U [user_name])

I didn't test this locally but if -d "${POSTGRES_DB}" evaluates where POSTGRES_DB is undefined this will produce -d with no value right? What happens in the psql case when -d is passed no parameter, or does the Postgres image automatically define POSTGRES_DB with the user internally so there's always a value?

nickjj avatar Jun 11 '25 21:06 nickjj

Yes, it produces -d with no value. Weird, it works and then just uses the same database name as what's POSTGRES_USER but if I directly try to input the evaluated command to terminal:

docker compose exec postgres psql -d -U postgres

It results in

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  database "-U" does not exist

I can modify the script to specify -d only if POSTGRES_DB has value

kennyhei avatar Jun 12 '25 06:06 kennyhei

I updated the script to include -d flag only if POSTGRES_DB is set

kennyhei avatar Jun 12 '25 06:06 kennyhei

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: database "-U" does not exist

That is what I thought would happen since it tries to pass -U in as an arg to -d. You can run docker compose exec postgres env to see what's available. The Postgres image does not always populate POSTGRES_DB.

nickjj avatar Jun 12 '25 10:06 nickjj

I'd have to also test this but I think Docker Compose now supports the same type of nested variable interpolation with a default so we can also do the same in the compose.yaml file so the POSTGRES_DB field doesn't need to be commented out by default.

Do you want to test that?

nickjj avatar Jun 12 '25 10:06 nickjj

I'd have to also test this but I think Docker Compose now supports the same type of nested variable interpolation with a default so we can also do the same in the compose.yaml file so the POSTGRES_DB field doesn't need to be commented out by default.

Do you want to test that?

Did the change and seems to work based on testing 👍

kennyhei avatar Jun 12 '25 12:06 kennyhei