How to use volume in docker compose for postgres?

About your docker-compose file

  1. First, I thought it’s because you don’t use the ‘links’ option to link your postgres container to the web container – it’s good practice if you don’t expand ports – but you expand postgres port.

  2. If you want to use inheritance from the image you posted

    Instead of using this line:

    my_image/postgresql:9.3

    use:

    docker/postgres
    

    and create path docker/postgres and there place Dockerfile with inheritance from the container you want.

  3. I always use shared 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 all your docker files structure to reproduce this error and fix it, so I created a 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:

  1. I will recommend use official postgres image

  2. 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 knows host dbpostgres (image name and domain name) now – I link them using links.

If you need database from existing container

If you need the database from your existing container just use the docker option cp to copy database locally:

docker cp posgres_test:/var/lib/postgresql /private/var/lib/postgresql

where /private/var/lib/postgresql is a path on your localhost.
You also need to change credentials to db in docker-compose to your old credentials.
You have to do it before running docker-compose because if db doesn’t exist, it will be created.

Any questions, let me know.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)