How to use PostgreSQL Docker Compose with Persistent Volume, you can define a services
block in your docker-compose.yml
file that specifies the configuration for your PostgreSQL service. This block should include the image for the PostgreSQL service, as well as any configuration options and environment variables that you want to set.
For example, the following docker-compose.yml
file sets up a PostgreSQL service using the official PostgreSQL image, and specifies that the data files for the database should be stored in a persistent volume named “postgres-data”:
version: '3'
services:
postgres:
image: postgres
volumes:
- postgres-data:/var/lib/postgresql/data
environment:
POSTGRES_DB: mydb
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
volumes:
postgres-data:
o create and start the PostgreSQL service, you can run the following command from the directory containing your docker-compose.yml
file:
docker-compose up -d
This will create the PostgreSQL service and the persistent volume, and start the PostgreSQL service in the background. You can then connect to the PostgreSQL service using a client like psql, and use the environment variables specified in the environment
block of the docker-compose.yml
file to authenticate.
To stop the PostgreSQL service, you can run the following command:
docker-compose down
This will stop the PostgreSQL service and remove the containers and volumes associated with the service. However, the data in the persistent volume will be preserved, so when you restart the service using docker-compose up
, the data will be available in the database.