Skip to content
DevOps

Connecting to Dockerized PostgreSQL: A Guide for PowerShell and Django

Learn how to interact with a PostgreSQL database running inside Docker using PowerShell and Django's dbshell, including essential environment configurations.

CodingBowl··2 min read
Photo by fabio on Unsplash

Learn how to interact with a PostgreSQL database running inside Docker using PowerShell and Django's dbshell, including essential environment configurations.

1. The Docker Setup

When your database lives in a container, your Windows host needs the PostgreSQL Client (not the full server) to use psql, or you must use Docker commands to "exec" into the container.

Ensure your docker-compose.yml or docker run command has mapped the ports correctly:

`ports:
- "5432:5432"

`

2. Configuring PowerShell for psql

Even with Docker, Django's python manage.py dbshell looks for a local psql executable on your Windows Path to connect to the container.

  1. Install the PostgreSQL command-line tools on Windows.

  2. Locate the bin folder (e.g., C:\Program Files\PostgreSQL\16\bin).

  3. Search for "Edit the system environment variables" in the Start Menu and add that path to the Path variable.

  4. Restart PowerShell.

3. Running Django dbshell with Docker

Since your DB is in Docker, ensure your Django settings.py points to localhost (if the port is mapped) or the Docker service name (if Django is also in Docker).

`# To enter the shell via Django:
python manage.py dbshell

`

If you prefer to skip the local install and go directly through Docker, use this PowerShell command:

`docker exec -it <container_name> psql -U <username> -d <database_name>
`

4. Common psql Commands and Examples

Use these commands inside your terminal to manage the containerized data:

List Databases

Command:

`\l`

Example: Run this to see if the database defined in your Docker environment variables was created.

Connect to Database

Command:

`\c database_name`

Example: \c my_django_db moves your session into the specific project database.

List Tables

Command:

`\dt`

Example: Use this to check if docker-compose up and your initial migrations created the expected tables.

Describe Table

Command:

`\d table_name`

Example: \d auth_user allows you to inspect the schema of the Django default user table.

Exit

Command:

`\q`

Example: Safely exit the psql interface and return to your Windows PowerShell prompt.