How to access the postgres of a Docker image?

Asked

Viewed 1,932 times

3

Greeting, I just created a Docker image of the Postgresql database with some additional settings as shown in the command below:

docker run -p 15432:15432 --name kwandb -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=MorangocomUva1 -e POSTGRES_DB=kwan -d postgres:10.5-alpine

The seat is running as you can see in the image below:

inserir a descrição da imagem aqui

I want to execute the command CREATE DATABASE guru99; in the Postgresql database, but this is a Docker image, as I will find in the database image to create the database?

I know how to do this when the database is installed locally on my operating system, but here is an image.

  • What does it mean -p 15432:15432 of your command?

  • means I’m running the database on port 15432

  • I just need to get into the container terminal of the postgres database

1 answer

3


Option 1:

You can use an interactive session using Docker exec:

Executes a command in a running container.

Use:
Docker exec [OPTIONS] CONTAINER COMMAND [ARGUMENT...]

For your case, just rotate the following:

docker exec -it kwandb psql -U postgres

This will start an interactive terminal in your running container by running the psql with the user you specified.


Option 2:

If you have the psql available on your host, you can use it to connect to the container on the port you have published. However you must first fix the docker run to steer the door correctly ( 0.0.0.0:15432->5432/tcp ):

docker run -p 15432:5432 --name kwandb -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=MorangocomUva1 -e POSTGRES_DB=kwan -d postgres:10.5-alpine

Once done, simply connect to the container using the exported port:

psql -h localhost -p 15432 -U postgres

The user password will be asked. If you want to skip this interactive step, set the variable PGPASSWORD along with the command:

PGPASSWORD='MorangocomUva1' psql -h localhost -p 15432 -U postgres

Note: Using the environment variable is not good security practice. For use in production environments, consider authentication via filing cabinet ~/.pgpass

  • Or connect via mapped port: localhost:15432

  • @Andersoncarloswoss suggestion added to the reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.