PostgreSQL everywhere

How to run SQL commands in a Postgre SQL Docker container?

This post was most recently updated on March 8th, 2022.

2 min read.

This article will explain how to run your arbitrary SQL commands against a Postgre SQL database running in a Docker container in Windows. That should be super simple, but since I never remember anything like this by heart, I had to google it ā€“ and turns out, either I didnā€™t know how to google this properly or people havenā€™t bothered to document this.

So, letā€™s fix that. But first, why did I need to do this, again?

Problem

So ā€“ I meant to run some SQL against a database I already had running in a Docker container. But I didnā€™t want to figure out what client I could be using, and I definitely didnā€™t want to develop a console application that would use a connection string and then run my SQL.

So I needed to figure out how to run the commands in the Docker container using the Docker CLI.

Solution

Here are the steps ā€“ theyā€™ll work using Docker Desktop on Windows.

Time needed:Ā 5 minutes

How to run SQL commands in a Postgre SQL Docker container?

  1. Run a container hosting the Postgre SQL server

    Something like this:
    docker run -d --name timescaledb -p 5432:5432 -e POSTGRES_PASSWORD=password timescale/timescaledb:latest-pg12

    (I know, I know, thatā€™s technically a TimescaleDB, but itā€™s built on Postgre, so..)

  2. Launch Docker CLI

    Hereā€™s where to do that in Docker Desktop, but you could do the same by having to run your container in interactive mode.



    Or using a console of your choice, itā€™ll look somewhat like this:
    docker exec -it TimescaleDB bash

    On Ubuntu, just add ā€œsudoā€, and it should work. šŸ˜¬

  3. Run Postgre terminal client

    This exact command will depend on the image ā€“ but at least psql is a good guess.

    You can start it by running something along the lines of:
    psql -h [host name] -U [user name]

    In my case:
    psql -h localhost -U postgres

    localhost being, obviously local server and the user name being something you may or may not be able to configure. ā€œpostgresā€ might be a good guess, but also you might want to check your connection string if you have one.

  4. Thatā€™s it. You can now run your SQL!

    Just remember to write the commands in UPPERCASE and end with a semi-colon, and you should be good. ā˜ŗ

And there you go! Hope itā€™s as helpful for you as itā€™s for me. šŸ™ˆ


References

mm
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments