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

Development
Friday, January 8, 2021

Run Postgres using "docker-compose"

Create a local directory called "postgres"

1$ mkdir postgres
2$ cd ./postgres

Create a "pgdata" directory inside "postgres" directory

1$ cd ./postgres
2$ mkdir ./pgdata

👉 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

1$ touch ./docker-compose.yml

📄 docker-compose.yml file

1version: "3.8"
2services:
3 db:
4 image: "postgres:13"
5 ports:
6 - "5432:5432"
7 volumes:
8 - ./pgdata:/var/lib/postgresql/data
9 environment:
10 - POSTGRES_USER=dbuser
11 - POSTGRES_PASSWORD=admin2021
12 - POSTGRES_DB=todoapp
  • This file creates a host called "db" from a Postgres version 13 image. The TCP port 5432 (postgres) of the host "db" is exposed externally as TCP port 5432.

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

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

Run the container in detached mode

1$ docker-compose up -d

List of running docker containers

1$ docker-compose ps

Run command inside the container

1$ docker-compose run db bash

Connect postgres inside the host

1$ psql --host=db --username=dbuser --dbname=todoapp

Connect to "postgres" from outside

1$ psql --host=localhost --username=dbuser --dbname=todoapp

stop container

1$ docker-compose down

Et voilà 🎉 !

Subscribe to our Newsletter

We deliver high quality blog posts written by professionals monthly. And we promise no spam.

elitizon ltd.

© 2020 elitizon ltd. All Rights Reserved.