Docker - How can run the psql command in the postgres container?

Solution 1:

docker exec -it yiialkalmi_postgres_1 psql -U project -W project

Some explanation

  • docker exec -it The command to run a command to a running container. The it flags open an interactive tty. Basically it will cause to attach to the terminal. If you wanted to open the bash terminal you can do this

docker exec -it yiialkalmi_postgres_1 bash

  • yiialkalmi_postgres_1 The container name (you could use the container id instead, which in your case would be 40e39bd0329a )

  • psql -U project -W project The command to execute to the running container

  • U user

  • W Tell psql that the user needs to be prompted for the password at connection time. This parameter is optional. Without this parameter, there is an extra connection attempt which will usually find out that a password is needed, see the PostgreSQL docs.

  • project the database you want to connect to. There is no need for the -d parameter to mark it as the dbname when it is the first non-option argument, see the docs: -d "is equivalent to specifying dbname as the first non-option argument on the command line."

These are specified by you here

environment:
    POSTGRES_DB: project
    POSTGRES_USER: project
    POSTGRES_PASSWORD: project

Solution 2:

If you need to restore the database in a container you can do this:

docker exec -i app_db_1 psql -U postgres < app_development.back

Don't forget to add -i.

:)

Solution 3:

You can enter inside the postgres container using docker-compose by typing the following

docker-compose exec postgres bash

knowing that postgres is the name of the service. Replace it with the name of the Postgresql service in you docker-compose file.

if you have many docker-compose files, you have to add the specific docker-compose.yml file you want to execute the command with. Use the following commnand instead.

docker-compose -f < specific docker-compose.yml> exec postgres bash

For example if you want to run the command with a docker-compose file called local.yml, here the command will be

docker-compose -f local.yml exec postgres bash

Then, use psql command and specify the database name with the -d flag and the username with the -U flag

psql -U <database username you want to connect with> -d <database name>

Baammm!!!!! you are in.