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

Table of Contents

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