Postgres in Docker

Docker makes it easy for us to spin up a PostgreSQL database on our server or local machine. Here’s how we can get started quickly:

🚀 Run PostgreSQL in a Docker Container

# Name, password, and local port (54320) can be changed as needed.
# This example uses the official Postgres Alpine image.
docker run --name mypostgres -e POSTGRES_PASSWORD=password -d -p 54320:5432 postgres:alpine

# To keep data persistent, we add a volume reference:
docker run --name mypostgres -v "$PWD"/data:/var/lib/postgresql/data -e POSTGRES_PASSWORD=password -d -p 54320:5432 postgres:alpine

🔗 Accessing the Container

🛠️ Use Docker Compose for Convenience

We can use a docker-compose.yml file to manage our containers more easily:

version: "3"
services:
  postgresdb:
    image: postgres:alpine
    container_name: "mypostgres"
    environment:
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'pgpass'
      POSTGRES_DB: 'postgres'
    ports:
      - "54320:5432"
    volumes:
      - ./db-data:/var/lib/postgresql/data

Start and stop our container with:

# Start the container
docker-compose up -d
# Stop the container
docker-compose down

🖥️ Add pgAdmin as a Service

We can add pgAdmin to our docker-compose.yml to manage our database via a web UI:

  pgadmin:
    image: dpage/pgadmin4
    ports:
      - '8080:80'
    external_links:
      - mypostgres:postgres
    environment:
      PGADMIN_DEFAULT_EMAIL: 'admin@example.com'
      PGADMIN_DEFAULT_PASSWORD: 'admin'

After running Docker Compose, we access pgAdmin at localhost:8080 in our browser.

To connect to our Postgres DB, click “Add New Server” in pgAdmin, enter a name, and use the connection details for our Postgres container. Save, and we’ll see our new connection in the sidebar.

Add new server

pgAdmin connections


For a complete example, see the full docker-compose file here.