Ready for another Mastodon guide? Well today we're going to go over how to migrate your PostgreSQL database to its own server in a few easy steps! This will remove quite a bit of the resource usage from your main Mastodon server since the database loves CPU and RAM.
Migrating PostgreSQL
Create a mastodon user on the new database server.
adduser --disabled-login mastodon
Install postgresql on your new database server.
wget -O /usr/share/keyrings/postgresql.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc
echo "deb [signed-by=/usr/share/keyrings/postgresql.asc] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/postgresql.list
apt update
apt install postgresql postgresql-contribEnable the services.
systemctl daemon-reload
systemctl enable postgresql@Edit the /etc/postgresql/15/main/postgresql.conf file and set the server's IP to the listen_addresses value and set the port to 5432.
Edit the /etc/postgresql/15/main/pg_hba.conf file and add the following line to the bottom of the file (substituting your Mastodon server's IP).
host all all MASTODON_SERVER_IP password
Restart the PostgreSQL service.
systemctl restart postgresql
Create the mastodon user in PostgreSQL and set a password.
sudo -u postgres psql
CREATE USER mastodon CREATEDB;
ALTER USER mastodon WITH PASSWORD 'password123';
qSwitch over to the mastodon user and create an empty database.
su - mastodon
createdb -T template0 mastodon_productionLogin to your Mastodon server and stop all of the Mastodon services.
systemctl stop mastodon-*
Switch over to the mastodon user and make a backup of your current PostgreSQL database.
su mastodon
cd;pg_dump -Fc mastodon_production -f backup.dumpCopy the backup file to the database server.
rsync -avz backup.dump root@DATABASE_SERVER_IP:/home/mastodon/backup.dump
Switch back to the database server and as the mastodon user import the database backup.
pg_restore -Fc -U mastodon -n public --no-owner --role=mastodon -d mastodon_production backup.dump
Switch back to the Mastodon server and edit the .env.production file with the database server IP address.
DB_HOST=DATABASE_SERVER_IP
Switch back to root and start the Mastodon services.
systemctl start mastodon-sidekiq
systemctl start mastodon-web
systemctl start mastodon-streaming
And that's all there is to it. Make sure you don't have any firewall rules blocking your connection between the servers and everything should be working properly with your PostgreSQL database on its own server now.
Go out and do good things! -KuJoe