0

I create an Dockerfile with Postgresql with this code:

FROM postgres:9.4
MAINTAINER Fabio Ebner
ENV POSTGRES_PASSWORD="dna44100"
ENV POSTGRES_PORT=5432
EXPOSE ${POSTGRES_PORT}
COPY init.sql /docker-entrypoint-initdb.d/

so How can I specify to always save my db data in my user Machine? cause with this code everty time I stop the container my data are lost

Fabio Ebner
  • 2,613
  • 16
  • 50
  • 77

2 Answers2

0

You will need to mount a volume. pointing your host machine to the container's directory /var/lib/postgresql

Source: docker mounting volumes on host

Eden Reich
  • 387
  • 2
  • 7
0

You need to mount a volume to the data directory of PostgreSQL.

You can use the following, using the docker-compose file:

version: "3"

services:
  test-postgresql:
    image: postgres:9.4
    container_name: test-postgresql
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PASSWORD: dna44100
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
      - ./folder-on-host:/var/lib/postgresql/data

With the docker-compose file you can start the container with docker-compose up and stop the container with docker-compose down. The database and settings are saved on the specified directory (./folder-on-host).

If you want to remove the volume you can use the command: docker-compose down -v


You can also use the docker run to mount a volume, using the -v or -volume option:

docker run -v ./folder-on-host:/var/lib/postgresql/data yourimagename
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
  • And in a single how can I do? Dockefile I create a VOLUME ["/Users/user/Projetos/docker/data"] . so when I run docker run myContainer he will create this dir? how I link this dir with a postgres dir inside my container? – Fabio Ebner Apr 13 '18 at 23:48