2

I am using postgres docker image in my project. For initialization I am using following command to create and init my database (tables, views, data, ...)

COPY sql_dump.sql /docker-entrypoint-initdb.d/

Is possible persist these data after container is stopped and removed? For instance when I run image of postgres, it will create database with these data wihout loading script every time of container start. Just load created data of first run.

I did some research and I found VOLUME command, but I don't know how to use it for my purpose, I am new with Docker. Thanks for any help. I am using Docker For Win v18.

Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174
  • Possible duplicate of [How can I initialize a MySQL database with schema in a Docker container?](https://stackoverflow.com/questions/29145370/how-can-i-initialize-a-mysql-database-with-schema-in-a-docker-container) – David Maze Jul 03 '18 at 15:11

1 Answers1

1

You can use docker named volumes more information can be found here.

this will create a named volume called postgres-data

docker volume create postgres-data 

and say this is your command to create the container.

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

change that to this.

docker run --name some-postgres  -v postgres-data:/var/lib/postgresql -e POSTGRES_PASSWORD=mysecretpassword -d postgres

this should mount the postgres-data volume under /var/lib/postgresql. can they initialize your DB and when you stop and start the container it will contain the persisted data.

-HTH

Ed Mendez
  • 1,510
  • 10
  • 14
  • you are using path like /var/lib/postgresql .. nevermind if I am on windows machine? – Denis Stephanov Jul 03 '18 at 14:47
  • Even if you are running docker on a windows machine, your docker containers will most likely be running linux. the path is relative to the container, not the host. – Ed Mendez Jul 03 '18 at 14:53
  • Oh, ok. So this path is path in thatr container, right? Not windows. – Denis Stephanov Jul 03 '18 at 14:57
  • @DenisStephanov correct. There is something else called host data volumes where you specify a path on windows, but that isn't this. You can find more info here; https://www.tricksofthetrades.net/2016/03/14/docker-data-volumes/ under host data volumes. – Ed Mendez Jul 03 '18 at 15:47