Running PostgreSQL in Docker and Accessing It from Your OS



This content originally appeared on DEV Community and was authored by coder7475

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.

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:16
  • --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:16 → 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:16
    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

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.


This content originally appeared on DEV Community and was authored by coder7475