Docker Compose postgres database

The last configuration file is docker-compose.yaml in the root of the project.

This Docker file creates two containers running a local Postgres database:

  • postgres: runs the actual postgres database (16-alpine)
  • pgadmin: runs a web interface to manage the database using pgAdmin

The configuration is based on awesome-compose.

docker-compose.yaml
version: "0.2"
name: app_docker

services:
  postgres:
    env_file: .env
    container_name: postgres
    image: postgres:16-alpine
    environment:
      - POSTGRES_USER=${POSTGRES_USER}
      - POSTGRES_PASSWORD=${POSTGRES_PW}
      - POSTGRES_DB=${POSTGRES_DB}
    ports:
      - 5435:5432

  pgadmin:
    env_file: .env
    container_name: pgadmin
    image: dpage/pgadmin4:latest
    environment:
      - PGADMIN_DEFAULT_EMAIL=${PGADMIN_MAIL}
      - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_PW}
    ports:
      - 5050:80

env_file references a .env file that contains the environment variables for the database. The project contains a .env.example file with the default values for the variables:

.env.example
POSTGRES_USER=postgres
POSTGRES_PW=postgres
POSTGRES_DB=postgres
PGADMIN_MAIL=example@mail.com
PGADMIN_PW=password

Having a local database allows to run the project locally without having to worry about any remote server.

During local development you can connect to the local database container by changing the configuration variables.

In production, you can then point to a remote database without changing any details of the code, but just updating the environment variables.

This configuration makes development easy, fast, and secure.