问题
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as the following:
Here is the relevant piece of docker-compose:
db_of_ivms:
image: postgres:10
restart: unless-stopped
ports:
- 5432:5432
container_name: db_of_ivms
environment:
POSTGRES_PASSWORD: xxx
POSTGRES_USER: ivms_usr
POSTGRES_DB: ivms_db
Nevertheless, I'm dealing with this error:
docker exec -it -u 0 db_of_ivms bash
# psql
psql: FATAL: role "root" does not exist
回答1:
You need shell in with the postgres user
docker exec -it -u postgres db_of_ivms bash
Now for containers that you dont specify POSTGRES_USER: ivms_usr:
postgres@d9b097b8db8c:/$ psql
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
(3 rows)
If you specify POSTGRES_USER: ivms_usr and Database (note psql command arguments):
docker exec -it -u postgres db_of_ivms bash
postgres@2cec2435bb83:/$ psql -U ivms_usr -d ivms_db
psql (10.12 (Debian 10.12-1.pgdg90+1))
Type "help" for help.
ivms_db=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
ivms_db | ivms_usr | UTF8 | en_US.utf8 | en_US.utf8 |
postgres | ivms_usr | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | ivms_usr | UTF8 | en_US.utf8 | en_US.utf8 | =c/ivms_usr +
| | | | | ivms_usr=CTc/ivms_usr
template1 | ivms_usr | UTF8 | en_US.utf8 | en_US.utf8 | =c/ivms_usr +
| | | | | ivms_usr=CTc/ivms_usr
(4 rows)
回答2:
I use this procedure for example for getting dump:
docker exec -it -u 0 <container-name> bash
Now, you could enter psql commands with root permission:
# pg_dump -U <user-name> <db-name> > dump.sql
回答3:
I've found an alternative manner through Django shell:
$ python manage.py shell
from django.db import connection
cursor = connection.cursor()
cursor.execute("DELETE FROM django_migrations WHERE app='settings'")
来源:https://stackoverflow.com/questions/60260782/how-to-execute-psql-interactive-in-its-docker-container