Making backups a part of your Forge deployments
You can use Forge's API to create new database backups on every deployment.
If you are using Laravel Forge for you server provisioning and management you might have noticed that there is a built-in backup feature that makes it easy to take database backups for your websites and apps.
We use these Forge backups specifically to prevent against bad deployments.
In the past we’ve come into situations where a new deployment has broken our Craft install leaving us unable to restore via the Craft command line. In these situations it’s good to be able to quickly revert to an earlier backup via the Forge dashboard as opposed to stressing out over mysql
or psql
restore commands.
Bear in mind we keep separate, long-term backups of both the database and asset folders using craft-remote-backup
One approach here is to either keep a set amount of hourly backups or just take a manual backup as part of our deployment process.
This isn’t ideal . We might forget to manually backup or our hourly backups might not be sufficient if we’ve been making a lot of changes to the site before deployment.
A better approach would be to automatically create a new Forge backup when deploying.
Automatic Deployment Backups
Luckily, Forge has an API we can hook into to do exactly that. Let’s use this API alongside our deployment script to create an automatic database backup on every new deployment.
Create API Access Token
First, create a new Forge API access token. Go to your avatar in the top right and hit Account followed by API:
Give your token a name and hit create. Make sure to take down the token now, as you won’t be able to see it again.
Create Backup Configuration
Now create a backup configuration. Go to your server and hit Backup in the sidebar. Enter your backup details.
For frequency select “Custom”. Unfortunately you have to give Forge some sort of cron schedule. In other words, there’s no way to say “don’t backup unless I do it manually”. So we usually create a cron schedule of 0 0 * * 0
which is once a week.
Create Your API Request
Now we need to generate the curl
request that we’ll make to the API.
We need:
- Server ID
- Backup ID
- API access token
- API endpoint
You can find the server ID down the bottom of the dashboard:
And you’ll find the backup ID on the backup page:
The API endpoint we want to use is the “run backup configuration” endpoint.
So let’s use all this to create a simple one line script on our server:
#!/bin/bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer [API ACCESS TOKEN]" https://forge.laravel.com/api/v1/servers/[SERVER ID]/backup-configs/[BACKUP ID]
~/deployment-backup.sh
Now add this to your deployment script in Forge:
And you’re good to go. Now every time you make a new deployment with Forge you’ll have a fresh backup of your database to revert to if things go wrong.