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?
- 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..) - 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. đŹ - 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. - 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
- https://docs.timescale.com/timescaledb/latest/how-to-guides/install-timescaledb/self-hosted/docker/installation-docker/
- https://www.postgresql.org/docs/8.2/server-start.html