How to persist data in a dockerized postgres database using volumes

后端 未结 4 617
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 01:32

My docker compose file has three containers, web, nginx, and postgres. Postgres looks like this:

postgres:
  container_name: postgres
  restart: always
  ima         


        
相关标签:
4条回答
  • 2020-11-28 01:37

    You can create a common volume for all Postgres data

     docker volume create pgdata
    

    or you can set it to the compose file

       version: "3"
       services:
         db:
           image: postgres
           environment:
             - POSTGRES_USER=postgres
             - POSTGRES_PASSWORD=postgress
             - POSTGRES_DB=postgres
           ports:
             - "5433:5432"
           volumes:
             - pgdata:/var/lib/postgresql/data
           networks:
             - suruse
       volumes: 
         pgdata:
    

    It will create volume name pgdata and mount this volume to container's path.

    You can inspect this volume

    docker volume inspect pgdata
    
    // output will be
    [
        {
            "Driver": "local",
            "Labels": {},
            "Mountpoint": "/var/lib/docker/volumes/pgdata/_data",
            "Name": "pgdata",
            "Options": {},
            "Scope": "local"
        }
    ]
    
    0 讨论(0)
  • 2020-11-28 01:45

    Strangely enough, the solution ended up being to change

    volumes:
      - ./postgres-data:/var/lib/postgresql
    

    to

    volumes:
      - ./postgres-data:/var/lib/postgresql/data
    
    0 讨论(0)
  • 2020-11-28 01:46

    I think you just need to create your volume outside docker first with a docker create -v /location --name and then reuse it.

    And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .

    0 讨论(0)
  • 2020-11-28 01:50

    I would avoid using a relative path. Remember that docker is a daemon/client relationship.

    When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database is then relative to the daemon, not the client.

    Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.

    In short, don't use a relative path, use an absolute path.

    0 讨论(0)
提交回复
热议问题