Skip to content

Instantly share code, notes, and snippets.

@BornPsych
Last active October 15, 2025 12:55
Show Gist options
  • Select an option

  • Save BornPsych/b31632519f5e7f2a14ccc359a3b170ca to your computer and use it in GitHub Desktop.

Select an option

Save BornPsych/b31632519f5e7f2a14ccc359a3b170ca to your computer and use it in GitHub Desktop.
docker postgres command

For Quickly running postgres database for monitoring - watch -n 0.1 "ps aux | grep [p]ostgres"

Pull docker image

docker pull postgres

Run docker image

docker run --name postges-container \                                                                           ✔
  -e POSTGRES_DB=mydb \
  -e POSTGRES_USER=myuser \
  -e POSTGRES_PASSWORD=mypassword \
  -p 5432:5432 \
  -d postgres

check database

psql -h localhost -p 5432 -U myuser -d mydb

Connect database to application

postgresql://myuser:mypassword@localhost:5432/mydb

Just in case you need persistance volume

docker run --name postgres-container \
-e POSTGRES_DB=mydb \
-e POSTGRES_USER=myuser \
-e POSTGRES_PASSWORD=mypassword \
-v pgdata:/var/lib/postgresql/data \
-p 5432:5432 \
-d postgres
Action Command
Restart container docker restart postgres-container
Stop container docker stop postgres-container
Start again docker start postgres-container
Remove container docker rm -f postgres-container
Check logs docker logs postgres-container
Access psql shell inside docker exec -it postgres-container psql -U myuser -d mydb
version: '3.9'
services:
postgres:
image: postgres
container_name: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
volumes:
- ./init-db:/docker-entrypoint-initdb.d
# docker compose up -d
# 1. Connect to a PostgreSQL database
psql -h localhost -p 5432 -U postgres -d mydb
# 2. List all databases
\l
# 3. Connect to another database
\c mydb
# 4. List all tables in the current database
\dt
# 5. Show all schemas
\dn
# 6. Describe a specific table (structure)
\d table_name
# 7. List all users/roles
\du
# 8. Execute a SQL file
\i path/to/file.sql
# 9. Clear the screen
\! clear
# 10. Quit psql
\q
-- 1️⃣ Create a new database
CREATE DATABASE mydb;
-- 2️⃣ Create a new schema
CREATE SCHEMA app_schema;
-- 3️⃣ Create a table inside the schema
CREATE TABLE app_schema.users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(150) UNIQUE,
created_at TIMESTAMP DEFAULT NOW()
);
-- 4️⃣ Insert sample data
INSERT INTO app_schema.users (name, email)
VALUES ('Yogesh Shahi', '[email protected]'),
('Alice', '[email protected]');
-- 5️⃣ Query the table
SELECT * FROM app_schema.users;
-- execute all at once `psql -h localhost -p 5432 -U postgres -d mydb -f setup.sql`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment