Run Postgres using "docker-compose"
Create a local directory called "postgres"
$ mkdir postgres
$ cd ./postgres
Create a "pgdata" directory inside "postgres" directory
$ cd ./postgres
$ 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
$ touch ./docker-compose.yml
📄 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
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
$ docker-compose up -d
List of running docker containers
$ docker-compose ps
Run command inside the container
$ docker-compose run db bash
Connect postgres inside the host
$ psql --host=db --username=dbuser --dbname=todoapp
Connect to "postgres" from outside
$ psql --host=localhost --username=dbuser --dbname=todoapp
stop container
$ docker-compose down
Et voilà 🎉 !
Top comments (3)
Thank you so much, it is very useful for newbies like me) At the same time, if I try
psql --host=db --username=dbuser --dbname=todoapp
, I get
psql: error: could not translate host name "db" to address: nodename nor servname provided, or not known
. Other commands work as expected. What does it mean and how to fix it?
Hi,
For me it's ok with:
psql --host=database --username=dbuser --dbname=todoapp
but I do not know why
question:
my set up is very similar, when booting up the container, and logining into psql with username db and host it create a different ip address for the database container every time, in the env of my project id have to constently change this. How could I hardcode localhost in the postgres docker-compose.yaml file, so that when ever i boot up the containers the db container will always host at 127.0.0.1?