How to Install PostgreSQL using Docker Compose

Docker Compose allows you to deploy and manage complex applications quickly.

I often use it for quickly managing databases while developing apps.

Here's how you can get PostgreSQL up and running using Docker Compose.

I'll assume you have Docker installed in this article (so if you don't, get Docker installed first).

Create a Docker Compose File

In your project, create a file named docker-compose.yml.

In the docker-compose.yml file, define a service for PostgreSQL. Here is a simple example:

version: "3.8"
services:
  db:
    container_name: codu-db
    image: postgres:16-alpine
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=secret
    ports:
      - "5432:5432"
    volumes:
      - db:/var/lib/postgresql/data
volumes:
  db:
    driver: local

This configuration starts a PostgreSQL container. You need to set a password for PostgreSQL (which I've set in the environment section), and I've also added a username.

We also map port 5432 on the host to port 5432 on the container and define a volume for persisting database data. Without the volume, your data won't persist.

Start the Container

To start the container, run the following command:

docker-compose up -d

This downloads the PostgreSQL image (if it's not already present) and starts the PostgreSQL container.

Connect to PostgreSQL

Once the container is up, you can connect to the PostgreSQL database using any PostgreSQL client.

Use localhost (or 127.0.0.1) as the host and 5432 as the port. Then, the username and the password are what you set in the docker-compose.yml file.

Bonus: Managing the Container

You can manage your PostgreSQL container using Docker Compose commands. For example, to stop the container, use:

docker-compose down

To view logs, use:

docker-compose logs

This should be perfect for running a database and developing things quickly and easily.

PostgresqlDocker
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.