-1

Let's say I have the following setup in my docker-compose.yml.

services:

  postgres:
    image: postgres:11.6
    env_file:
      - .local.env
    volumes:
      - ./database/:/docker-entrypoint-initdb.d
    ports:
      - 5432:5432
    ...

where ./database contains some SQL files that initialize the database. Here's my question... is initdb run every single time the stopped postgres container starts running again (via $ docker-compose up).

Thus, is it fair to say that every time I restart my postgres container, it builds the entire database from scratch all over again?

My guess is 'yes' as in the documentation it says

The default postgres user and database are created in the entrypoint with initdb.

zsolt
  • 1,233
  • 8
  • 18
Noah Stebbins
  • 385
  • 1
  • 11
  • If you don't declare somewhere to persist the data, it will get lost when the container is deleted and recreated. See also [How to persist data in a dockerized postgres database using volumes](https://stackoverflow.com/questions/41637505/how-to-persist-data-in-a-dockerized-postgres-database-using-volumes). – David Maze Feb 20 '21 at 17:38

1 Answers1

1

The answer is no, when you stop your container it is not deleted, only stopped, you can start it when it is stopped the same when you stop your computer it will not vanish from your desk :) You can even restart it when it is running, same as you would do with your computer.

However when you remove/delete the container with

docker rm -f containername

or

docker-compose rm

then it is truly deleted, equivalent of making your computer vanish from your desk.

But even than you can still persist your data with volume mounts, for example in your compose file your ./database directory will not be deleted from your host machine even when you delete the containers using it. It is the equivalent of using an external usb drive in your computer, so when you make your computer vanish from your desk with deleting it, you still have your usb drive with the data on it that was there when you still had your computer.

So you can persist your database files with the same technique in a volume mount like this:

services:

  postgres:
    image: postgres:11.6
    env_file:
      - .local.env
    volumes:
      - ./database/:/docker-entrypoint-initdb.d
      - ./postgres-data/data:/var/lib/postgresql/data
    ports:
      - 5432:5432
    ...

This way when you delete your container(s) and do "docker-compose up" again for the same compose file, postgres will not run its init scirpt because the /var/lib/postgresql directory is already populated in it.

However, my computer analogy is valid only in this context, please do not think of containers being mini computers or mini virtual machines, they are not! But that's an other discussion.

E_net4
  • 27,810
  • 13
  • 101
  • 139
zsolt
  • 1,233
  • 8
  • 18