How to use volume in docker compose for postgres?
About your docker-compose file
Firstly I thought it's because you don't use 'links' option to link your postgres container to web container - it's good practice if you don't expand ports - but you expand postgres port.
If you want use inheritance from the image you postedInstead of using this line:
my_image/postgresql:9.3
use:
docker/postgres
and create path docker/postgres and there place Dockerfile with inharitance from container you want.
I always use sharing volumes in docker-compose.yml like this:
.:/var/www/html
where .
is my project path where I place my code files.
Image I created to test this case
I don't have your all docker files structure to reproduce this error and fix it, so I created docker-compose which should match your needs or help to fix your issue:
version: '2'services: web: build: docker/web ports: - "8080:8080" links: - dbpostgres volumes: - .:/var/www/html # I will share my code so I map this path dbpostgres: image: postgres volumes: - /private/var/lib/postgresql:/var/lib/postgresql ports: - "5432:5432" environment: POSTGRES_USER: pguser POSTGRES_PASSWORD: pguser POSTGRES_DB: pgdb
Notes:
I will recommend use official postgres image
I left comments next to the lines.
How I made connection:
host=dbpostgres port=5432 dbname=pgdb user=pguser password=pguser
Because my web container know host dbpostgres(image name and domain name) now - I link them using links.
If you need database from existing container
If you need database from your existing container just use option docker cp to copy database localy:
docker cp posgres_test:/var/lib/postgresql /private/var/lib/postgresql
where /private/var/lib/postgresql
is path on your localhost.You need also change credentials to db in docker-compose to your old credentials.You have to do it before run docker-compose because if db doesn't exist, will be crated.
Any questions, let me know.
If the volume is external and already existing before the use of docker-compose you should declare it external, or else docker compose will create a new volume with the project name as prefix.
volumes: test_volume: external: true
Docs for external
using compose v3 (mostly similar to v2): https://docs.docker.com/compose/compose-file/compose-file-v3/#external
I think it sould be something like this for you.
docker run -itd -p 5432:5432 --name postgres_test -v /path/in/your/host :/path/in/your/container postgres_test psql -h 192.168.99.100 -p 5432 -U pguser -W pgdb
Read Docker docs(https://docs.docker.com/engine/tutorials/dockervolumes/), watch tutorials (there is a Docker Youtube channel whith great tutorials) and read other topics before posting a new one...