How to create a docker container that persists data?

Say you have a container that is hosting a database service and you want to persist the data so that it is not lost in the event that the container is stopped or killed. The solution to this problem is to use docker volumes. Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. As stated on the docker website: "Volumes are often a better choice than persisting data in a container’s writable layer, because a volume does not increase the size of the containers using it, and the volume’s contents exist outside the lifecycle of a given container". More information about volumes and docker containers can be found here.

So, here is an example of a compose file that you can use for a database that will mount a volume and persist that across the lifecycle of the container.

docker-compose.yml - sample

version: "3.6"
services:
  database:
    image: example-db
    networks:
      static-network:
        ipv4_address: 172.30.0.3
    build:
      context: .
      dockerfile: database.Dockerfile
    command: postgres -c 'max_connections=5'
    environment:
      - POSTGRES_USER=test
      - POSTGRES_PASSWORD=<omitted>
      - POSTGRES_HOST_AUTH_METHOD=trust
      - POSTGRES_DB=testdb
      - POSTGRES_SCHEMA=backup.sql
    volumes:
      - /mnt/databases/db/:/var/lib/postgresql/data
      - /mnt/db_backups/:/var/tmp/database_files
networks:
  static-network:
    ipam:
      config:
        - subnet: 172.30.0.0/16

That’s all for this blog post! I hope that you learned something new! ☺️

Previous
Previous

How to resolve FATAL: Peer authentication failed for user “postgres”

Next
Next

How to generate a random password?