How to enable archive mode in PostgreSQL

In this article, we will see how to enable archive mode in PostgreSQL. Archive mode is not enabled by default in PostgreSQL.

What is archiving

Archiving is the concept to store history in a safe location. This also helps with Point In Time Recovery(PITR) and also in situations where a standby is lagging behind the primary and requires the recently removed WAL segments to get back to sync.

Steps to enable archive mode in PostgreSQL:

1. Verify archive mode is enabled or not using below command.

show archive_mode;

How to enable archive mode in PostgreSQL

2. Set archive_mode to ON using ALTER SYSTEM command.

ALTER SYSTEM SET archive_mode to 'ON';

To effect these changes, we have to restart PostgreSQL.

3. Restart PostgreSQL server by using any of below commands.

sudo systemctl restart postgresql

or

pg_ctl -D $PGDATA restart -mf

4. Now, verify archive mode is enabled or not using same above command which we ran in the step 1.

5. Lets create archive directory and set the ownership to user postgres.

Run these commands with root or with sudo user.

mkdir -p /backups/archive chown postgres:postgres /backups/archive/

6. Now set the archive_command with a script that copies archives to a safe location which we have created.

ALTER SYSTEM SET archive_command TO 'cp %p /backups/archive/%f';

7. To take effect the above change, we have to reload SIGHUP by running below command.

SELECT pg_reload_conf();

8. Now, check archive directory and verify wals copied or not.

ls -ltrh /backups/archive

So in this article, we have seen how to enable archive mode in PostgreSQL step by step.