Running PostgreSQL in Docker and Accessing It from Your OS
PostgreSQL is one of the most popular relational databases, widely used in modern applications for its reliability and powerful features. Running it inside Docker makes local development and testing much easier, as you can quickly spin up and tear down isolated environments.
In this post, we’ll see how to:
- Run PostgreSQL inside a Docker container.
- Use Docker Compose for easier setup.
- Connect to PostgreSQL from your local machine.
- Get the connection URI for your applications.
Running PostgreSQL with Docker
You can start PostgreSQL with a single docker run
command:
docker run --name postgres-container \
-e POSTGRES_USER=admin \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=mydb \
-p 5432:5432 \
-d postgres:15
-
--name postgres-container
→ assigns a name to the container. -
POSTGRES_USER
,POSTGRES_PASSWORD
,POSTGRES_DB
→ environment variables for setup. -
-p 5432:5432
→ maps PostgreSQL’s port to your host machine. -
postgres:15
→ uses the official PostgreSQL image (version 15).
Once started, you can connect with:
psql -h localhost -U admin -d mydb
It will prompt for the password (secret
).
Using Docker Compose
Instead of remembering a long docker run
command, we can use docker-compose for a cleaner setup.
Create a file named docker-compose.yml
:
version: "3.9"
services:
postgres:
image: postgres:15
container_name: postgres-container
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
POSTGRES_DB: mydb
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Run it with:
docker-compose up -d
This will:
- Start PostgreSQL in a container.
- Expose it on port 5432.
- Persist data in a Docker volume so it isn’t lost when the container restarts.
Connecting from Your OS
Now you can connect using any PostgreSQL client:
From terminal:
psql -h localhost -U admin -d mydb
From GUI tool (like pgAdmin, DBeaver, or TablePlus):
-
Host:
localhost
-
Port:
5432
-
User:
admin
-
Password:
secret
-
Database:
mydb
Connection URI
For use in applications, you’ll often need the full PostgreSQL connection URI.
From your host machine:
postgresql://admin:secret@localhost:5432/mydb
From another service inside the same Docker Compose network:
postgresql://admin:secret@postgres:5432/mydb
(where postgres
is the service name defined in docker-compose.yml
).
Wrapping Up
Running PostgreSQL with Docker makes your development environment consistent, portable, and easy to manage. With Docker Compose, you get reproducible configurations and persistent storage with minimal effort.
You can now connect directly using psql
, GUI clients, or application frameworks by providing the connection URI.
Top comments (0)