Run PostgreSQL as service with docker compose

PostgreSQL can be run as service with help of docker compose for development purpose, so that no need to do regular installation and it can be easily used by other application running at your host or in docker container.

docker-compose.yml

version: "3.3"
services:
db:
image: postgres:9.4.1
ports:
- "5432:5432"
networks:
- dev_net
environment:
- POSTGRES_PASSWORD=password
volumes:
- pg_conf:/etc/postgresql
- pg_log:/var/log/postgresql
- pg_data:/var/lib/postgresql/data
networks:
dev_net:
external:
name: dev_net
volumes:
pg_data:
pg_conf:
pg_log:

We have defined external network ‘dev_net’, any container can be connect to PostgreSQL from this network. Also port 5432 forwarded to host 5432. You can connect to PostgreSQL by host 127.0.0.1.

Run the service.

docker-compose up -d

Make sure the service running.

docker ps

Check the connection from SQL Client.

Check with psql client.

psql -h 127.0.0.1 -U postgres  -d

This will connect to postgresql. Also application runs inside docker container can be connect to this postgres by host ‘db’. Make sure the container and db are in the same network ‘dev_net