Commit 77026536 authored by Simon Cornet's avatar Simon Cornet
Browse files

feat: add postgresql backup & restore snippets

parent 0096c7dc
Loading
Loading
Loading
Loading
Loading
+66 −0
Original line number Diff line number Diff line
# Postgresql Backup and Restore in Docker

## Make pg backup

```shell
docker exec -e PGPASSWORD='<SuperSecure>' <ContainerName> \
  pg_dump -U <PostgresRole> -d <PostgresDB> -Fc -f /tmp/database.dump
```

## Copy backup to root

```shell
docker cp <ContainerName>:/tmp/database.dump /root/database.dump
```

## Stop and remove old container

```shell
docker stop <ContainerName>
docker rm <ContainerName>
```

## Remove old database files

```shell
rm -rf /mnt/<PostgresDBDatadir>/
mkdir /mnt/<PostgresDBDatadir>/
chown 999 /mnt/<PostgresDBDatadir>/
chmod 700 /mnt/<PostgresDBDatadir>/
```

## Start new container
```shell
docker run \
  --name <ContainerName> \
  --detach \
  --restart unless-stopped \
  --network <ContainerNetwork> \
  --volume /mnt/<PostgresDBDatadir>:/var/lib/postgresql/data \
  --env POSTGRES_DB=<PostgresDB> \
  --env POSTGRES_USER=<PostgresRole> \
  --env POSTGRES_PASSWORD=<SuperSecure>
  docker.io/library/postgres:17
```

## Copy backup to new container

```shell
docker cp /root/database.dump <ContainerName>:/tmp/database.dump
```

## Verify role and db

```shell
docker exec -e PGPASSWORD='<SuperSecure>' <ContainerName> \
  psql -U <PostgresRole> -c "CREATE ROLE <PostgresRole> WITH LOGIN PASSWORD '<SuperSecure>';"
docker exec -e PGPASSWORD='<SuperSecure>' <ContainerName> \
  psql -U <PostgresRole> -c "CREATE DATABASE <PostgresDB> OWNER <PostgresRole>;"
```

## Restore backup

```shell
docker exec -e PGPASSWORD='<SuperSecure>' <ContainerName> \
  pg_restore -U <PostgresRole> -d <PostgresDB> -Fc /tmp/database.dump
```