DEV Community

loading...
Cover image for Postgres up and running in less than 3 minutes with docker-compose 🚀

Postgres up and running in less than 3 minutes with docker-compose 🚀

raphaelmansuy profile image Raphael MANSUY Originally published at elitizon.com ・1 min read

Run Postgres using "docker-compose"

Create a local directory called "postgres"

$ mkdir postgres
$ cd ./postgres
Enter fullscreen mode Exit fullscreen mode

Create a "pgdata" directory inside "postgres" directory

$ cd ./postgres
$ mkdir ./pgdata
Enter fullscreen mode Exit fullscreen mode

👉 As a docker container is "stateless" we must create the directory "pgdata" to keep the data when the container is shut down.

Create a file called "docker-compose.yml" in "postgres" directory

$ touch ./docker-compose.yml
Enter fullscreen mode Exit fullscreen mode

📄 docker-compose.yml file

version: "3.8"
services:
  db:
    image: "postgres:13"
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=dbuser
      - POSTGRES_PASSWORD=admin2021
      - POSTGRES_DB=todoapp
Enter fullscreen mode Exit fullscreen mode
  • This file create a host called "db" from a Postgres version 13 image. The TCP port 5432 (postgres) of the host "db" is exposed externally as the TCP port 5432.

  • The local directory "./pgdata" is mapped as the "/var/lib/postgressql/data" inside the "db" host

  • The user, password and database name are exposed as an environment variable

Run the container in detached mode

$ docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

List running docker containers

$ docker-compose ps
Enter fullscreen mode Exit fullscreen mode

Run command inside the container

$ docker-compose run db bash
Enter fullscreen mode Exit fullscreen mode

Connect postgres inside the host

$ psql  --host=db --username=dbuser --dbname=todoapp
Enter fullscreen mode Exit fullscreen mode

Connect to "postgres" from outside

$ psql --host=localhost --username=dbuser --dbname=todoapp
Enter fullscreen mode Exit fullscreen mode

stop container

$ docker-compose down
Enter fullscreen mode Exit fullscreen mode

Et voilà 🎉 !

Discussion

pic
Editor guide