DEV Community


Posted on • Updated on


Access the PostgreSQL in Docker Container

The use of Docker containers made our lives so easy. Not only the work of the sysadmin but work of the developer too.

However, these days I had to access the PostgreSQL that runs in a Docker container and had a bit of trouble, by inexperience and lack of knowledge until then.

Well, all is hard when we don't have the knowledge to do it. And to access the PostgreSQL in a Docker container is a piece of cake.

Firstly, we need to check if the container is up! We can do it with the following command line:

docker container ps
Enter fullscreen mode Exit fullscreen mode

The answer to this command is:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES

56fa1b0f91d7        ba5ab22916de        "docker-entrypoint.s…"   24 hours ago        Up 5 minutes>5432/tcp   my_database
Enter fullscreen mode Exit fullscreen mode

With the container running, as shown above, it is enough to run the following command line:

docker exec -it my_database bash
Enter fullscreen mode Exit fullscreen mode

Where my_database, in this case, is the Docker container NAME. We cuold use the container ID instead of the container NAME. In this context, we enter the container as the root user and now we can run the following command line:

psql -U postgres
Enter fullscreen mode Exit fullscreen mode

Ready! We are in PostgreSQL and we can create users, databases, tables and all we need to do our work. This fact is demonstrated by the change of the prompt to:

Enter fullscreen mode Exit fullscreen mode

I hope this small tip helps another person the same way it helped me as well.

Latest comments (1)

biriyanist profile image

Good read!
How can I access the same in one of the localhost port?

The AI Brief

AI generated git commit messages

Minimize the struggle of remembering what you just coded. AI-generated commits make it easier to manage projects and keep track of changes. The Nutlope/aicommits project demonstrates how AI can improve commit messages.

I open sourced an AI that creates any UI in seconds

Make AI-generated user interfaces a breeze. This open-source project harnesses the power of generative AI technologies like chatGPT to create versatile, quick, and intuitive UI components.

Use AI to commit like a PRO in 1 second

Upgrade your commit message game with AI. Boost your productivity by using ChatGPT to generate commit messages and avoid context switching. OpenCommit is an open-source library that helps you achieve this easily.

Build your own ChatGPT starter kit

Train AI models on custom data for improved domain-specific knowledge. Combine the power of WebView technologies and this starter kit to train your ChatGPT model on specific websites, allowing for better-optimized outcomes.