How to prevent data loss when a Postgres container is killed or shut down.

how-to-prevent-data-loss-when-a-postgres-container-is-killed-or-shut-down.

I do not like to make my blog contents so long when I can easily go straight to the point.

The simple answer to this problem is simply docker volume

Why Docker Volume

The main concept behind using Docker volumes for backups is to create a copy of the data outside the container. Each time the container is restarted, the data is copied from the local system into the Docker container file system. This ensures that the data is always up-to-date and consistent with the latest changes.

How To Create Docker Volume for PostgreSQL

  1. To create a Docker volume for PostgreSQL, use the following command:
 docker volume create pgdata

This will create a new Docker volume called pgdata that you can use to store the data for your PostgreSQL container.

  1. Start a new PostgreSQL container using the following command:
docker run -d --name postgresql -v pgdata:/var/lib/postgresql/data postgres:latest

This command starts a new PostgreSQL container called postgresql and maps the pgdata volume to the /var/lib/postgresql/data directory in the container. This means that the data stored in the container will be stored in the pgdata volume, which is separate from the container and will persist even if the container is deleted or restarted.

If the container is deleted or restarted, you can simply start a new container and map the pgdata volume to the /var/lib/postgresql/data directory again, and your data will be restored. You do not need to create backups of your data or copy the data back into the container manually.

Also you can check the docs for more information on docker volumes.

I usually use docker volume for development, but I have not really considered its importance when it comes to production if I won’t be using a postgres container. I don’t know about you? Tell me what you think in the comment section.

Also, if you found this post helpful, please consider giving it a like or sharing it with others who may be facing a similar issue. Thanks for reading!

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
what-it-was-like-to-code-for-amazon-(part-2)

What It Was Like To Code For Amazon (Part 2)

Next Post
my-takes-on-eslint-and-prettier-against-typescript

My takes on EsLint and Prettier against TypeScript

Related Posts