Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingforentrepreneurs/a3e762ae949ea69b9a68928b84cda547 to your computer and use it in GitHub Desktop.
Save codingforentrepreneurs/a3e762ae949ea69b9a68928b84cda547 to your computer and use it in GitHub Desktop.
How I use Postgres for Each new project with Docker Compose
version: '3.9'
services:
  db:
    image: postgres
    restart: always
    ports:
        - 5430:5432
    volumes:
        - my_pg_v:/var/lib/postgresql/data/
    environment:
        - POSTGRES_DB=mydb
        - POSTGRES_PASSWORD=mypass
        - POSTGRES_USER=myuser

volumes:
  my_pg_v:

networks:
  default:
    name: my_custom_network

This yields: postgres://myuser:mypass@localhost:5430/mydb

Running

  • docker compose pull - gets the lastest postgres image
  • docker compose up - runs the postgres database via Docker compose in the foreground (e.g. blocking)
  • docker compose up -d - runs the postgres database via Docker compose in the background (e.g. non-blocking). This blocks the PORT value too.

View what's running

  • docker compose ps -- see all docker compose services that are running
  • docker ps -- see all docker containers that are running (similar but different)

Stopping what's running

  • docker compose down - stop + keep database data. Frees up the PORT value (regardless of how docker compose is running)
  • docker compose down --rmi all -v - DANGER - this will stop the database running AND delete all data.

Using other compose files:

  • docker compose -f compose.other.yaml Anything after -f needs to be a docker compose file. Consider using this for staging.

Example client:

export PGPASSWORD=mypass  
psql postgres://myuser@localhost:5430/mydb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment