๐ŸŽ New User? Get 20% off your first purchase with code NEWUSER20 ยท โšก Instant download ยท ๐Ÿ”’ Secure checkout Register Now โ†’
Menu

Categories

Migrate a Linux Web Server to a New VPS with Minimal Downtime

Migrate a Linux Web Server to a New VPS with Minimal Downtime

Your provider is ending the contract, or the OS on the box went out of support last spring. Either way you have one VPS running nginx, a PHP or Node app, MariaDB or PostgreSQL, Let's Encrypt certificates and a handful of cron jobs, and you need to migrate a Linux server to a new VPS without a long outage. Nobody remembers everything that was installed by hand over the years.

Copying files is the easy part. The outage comes from the cron job nobody wrote down, the firewall rule that quietly made a service reachable, or the certbot hook that reloads nginx after renewal. The fix is a runbook, not a clever rsync command, and the first page of it is an honest inventory of the old machine.

Inventory what the old server really does

Run everything below on the old server as root and keep the output. The goal is a plain text file, for example ~/migration/inventory.txt, that becomes the skeleton of your runbook. Every line in it is something to rebuild, something to copy, or something you have consciously decided to drop.

Services, ports and who talks to them

Listeners reveal services you forgot about. Established outbound connections reveal dependencies: a remote database, an SMTP relay, a payment API.

ss -tulpn
ss -tnp state established
systemctl list-unit-files --state=enabled
docker ps --format '{{.Names}}\t{{.Image}}\t{{.Ports}}'
find /srv /opt /home -name 'compose*.y*ml' -o -name 'docker-compose*.y*ml'
nft list ruleset        # or: iptables-save

Sample the outbound connections more than once, including during a busy hour. A nightly job will not show up at noon.

Write down every outbound destination and ask who allowlists your IP. SMTP relays, payment providers and managed database firewalls often do, and they will reject the new address until you update them. The same applies in reverse for partners that call your server.

Scheduled jobs, local users and hand-installed software

Cron lives in more places than crontab -e. Check every user, the system directories and systemd timers.

for u in $(cut -d: -f1 /etc/passwd); do echo "== $u"; crontab -u "$u" -l 2>/dev/null; done
ls -l /etc/cron.d /etc/cron.daily /etc/logrotate.d
systemctl list-timers --all
getent passwd | awk -F: '$3 >= 1000 && $3 < 65534'
apt-mark showmanual        # or: dnf history userinstalled
find /usr/local /opt -maxdepth 2
find /etc -type f -mtime -365
cat /etc/fstab; findmnt --real
ls -l /etc/letsencrypt/renewal-hooks/*

Each human or service account may own files, a crontab and SSH keys. Anything under /usr/local or /opt came from outside the package manager, so you will have to reinstall it deliberately. The find /etc output is noisy, but it is the quickest way to spot hand-edited config. Check /etc/fstab for extra disks or NFS mounts, and open the certbot renewal hooks: a deploy hook that reloads nginx is easy to forget.

Lower the DNS TTL and build the target to match

Do the DNS change first, because it costs nothing and has a waiting period. Build the new server while the clock runs.

Drop the TTL at least one old TTL ahead of cutover

$ dig +noall +answer example.com
example.com.    86400   IN  A   203.0.113.10

Resolvers cache a record for the TTL they last saw (RFC 1035 defines this), so a resolver that fetched the record a minute before your edit keeps it for up to 86400 seconds. Lower the TTL to 300 at least one full old TTL before the cutover. With the value above, that means a day ahead. Do it for every record that will move: the apex, www, and any API or mail hostnames. Confirm against the authoritative server with dig +noall +answer example.com @ns1.your-dns.example, not just your local resolver.

Provision the new VPS with matching users, packages and time settings

Use the same or a newer OS release, but keep the same major versions of the database and language runtime where you can. If you want to upgrade PostgreSQL or PHP too, make that a separate step after the move, so a failure has one cause.

Create service users with the same numeric IDs before any data arrives, so rsync --numeric-ids produces correct ownership:

groupadd -g 1001 deploy
useradd -u 1001 -g 1001 -m -s /bin/bash deploy
hostnamectl set-hostname web1.example.com
timedatectl set-timezone Europe/Berlin
apt-get install chrony && chronyc tracking

Install packages from your manual list, reviewing it first. It will include things you now want to drop. An Ansible playbook is worth it if your team already uses one, but do not write one just for this move.

For the transfer itself, generate a dedicated key on the old server and authorise it on the new one with restrictions, for example restrict,command="rrsync /" ssh-ed25519 AAAA... migration in root's authorized_keys. The rrsync helper ships with rsync, though its path varies by distribution. Delete the key when you finish. For the wider server setup, see VPS Server Setup 2026.

First sync: copy files while the old server stays live

The first pass moves the bulk of the data while users keep working. It can take hours and nothing breaks if it is slow.

rsync flags that preserve what matters

Run it as root on the old server, with a dry run first:

rsync -aHAXn --numeric-ids --info=progress2 --delete-after -e ssh /var/www/ new:/var/www/
rsync -aHAX  --numeric-ids --info=progress2 --delete-after --bwlimit=20000 \
      --exclude='/storage/framework/cache/' -e ssh /var/www/ new:/var/www/
  • -a keeps permissions, times, symlinks and owners. -H keeps hard links, -A ACLs, -X extended attributes.
  • --numeric-ids sends raw UID/GID instead of mapping names, which is why you matched IDs earlier.
  • The trailing slash on /var/www/ means "the contents of". Without it you get /var/www/www.
  • --delete-after removes files on the target that are gone from the source. Check the destination path twice.
  • --bwlimit is in KiB/s and keeps the sync from starving production.

If the two distributions differ on SELinux, run restorecon -Rv /var/www on the target afterwards. The rsync manual documents every option.

Exit code 24 means some source files vanished mid-transfer, which is normal for temp files and caches. Code 23 means a partial transfer: read the error lines, because it often means unreadable files. Run the same command later and only the deltas move.

What not to copy: /etc wholesale, /var/lib databases, caches

Copy the data directories in a loop, then pick specific config paths with -R so they keep their full path:

for d in /home /srv /opt /usr/local; do
  rsync -aHAX --numeric-ids --delete-after -e ssh "$d/" "new:$d/"
done
rsync -aHAXR --numeric-ids -e ssh /etc/nginx /etc/letsencrypt /etc/cron.d \
      /etc/fail2ban/jail.local /etc/systemd/system/myapp.service new:/

Do not copy /etc wholesale. It holds the new host's fstab, network config, SSH host keys and package-specific files that differ between releases. Pull the old tree to a scratch directory on the new server and review it with diff -ru /root/old-etc /etc. After copying units, run systemctl daemon-reload and enable them explicitly.

Never rsync /var/lib/mysql or /var/lib/postgresql from a running database: you get a torn, unrecoverable copy. Databases need a dump or replication, which is the next step. Skip caches and logs too.

The Linux Server Migration Handbook goes deeper on this ground.

Move the database without copying live data files

Dump and restore for small and medium databases

If a restore takes minutes, a logical dump is the safest route. It is consistent, portable and leaves the source untouched. On MariaDB or MySQL, pull it straight into the new server, with credentials in ~/.my.cnf on both sides:

ssh old 'mysqldump --single-transaction --routines --events --triggers --all-databases' | mysql

--single-transaction gives a consistent snapshot only for InnoDB. Find leftover MyISAM tables with information_schema.TABLES (ENGINE='MyISAM'), then convert them or accept --lock-all-tables, which blocks writes during the dump.

PostgreSQL keeps roles outside the individual databases, so restore those first. Otherwise ownership and grants fail with "role does not exist" errors:

ssh old 'pg_dumpall --globals-only' | psql -U postgres
createdb -O app app
ssh old 'pg_dump -Fc app' | pg_restore -d app

The piped form is single-threaded, because pg_restore -j 4 needs a seekable file. For bigger databases, dump to disk and restore with -j 4. The pg_dump documentation covers the formats.

Then verify: compare row counts on your key tables on both servers, run pg_restore --list on the archive, and check that encoding and collation match. Restoring into a newer major version works, an older one does not. Copy tuning values from my.cnf or postgresql.conf deliberately, because the new box probably has different RAM.

Replication when the dump takes too long

If you dump at cutover, restore time is your downtime. Rehearse with time on real data before choosing this route.

For PostgreSQL on the same major version, build a streaming replica:

pg_basebackup -h old -U replicator -D /var/lib/postgresql/16/main -R -X stream -P

Across major versions, use logical replication, which needs primary keys on replicated tables. For MariaDB or MySQL, seed from a dump that records the binlog position or GTID (the flag is --master-data or --source-data, depending on version), then start replication. At cutover, stop writes, wait for zero lag, promote the replica and repoint the app.

Test the new server before DNS points at it

Hit the new IP with the real hostname

curl --resolve sends the real hostname for SNI and the Host header, so certificates and virtual hosts behave as they will in production:

curl -sI --resolve example.com:443:203.0.113.20 https://example.com/
curl -skI --resolve example.com:443:203.0.113.20 https://example.com/
diff <(curl -s --resolve example.com:443:203.0.113.20 https://example.com/) \
     <(curl -s https://example.com/)

Use -k only to separate a TLS problem from an app problem. Expect the diff to show tokens and timestamps, but a missing asset or error page stands out. For browser testing, add a temporary line to /etc/hosts and remove it afterwards. On the server, run nginx -t, systemctl status, journalctl -u myapp -n 50 and ss -tlnp. Then scan the ports from outside, since a local listener says nothing about the firewall.

Certificates, mail and cron: the three things that break quietly

  • Certificates: rsync -a preserves the symlinks in /etc/letsencrypt/live. HTTP-01 renewals only succeed once DNS points here, so run certbot renew --dry-run after cutover, or issue ahead with DNS-01. Confirm the deploy hook reloads nginx.
  • Cron and timers: keep them off until cutover with systemctl mask --now backup.timer and commented crontab lines. Otherwise customers get duplicate emails and billing runs twice.
  • Mail: the new IP needs a PTR record, an updated SPF record, and outbound port 25 open, since many providers block it by default. Linux Mail Server Configuration covers the details.

Also replicate the firewall rules and update third-party allowlists for the new IP now, not during the cutover.

The cutover runbook, in order

Write this down with real clock times before you start. The numbers below are offsets from the moment you freeze writes (T+0), and the go/no-go point is the only decision that matters on the night.

Freeze writes and run the final sync

  1. T-24h: announce the window to users and anyone who calls your API.
  2. T+0: put the old app in maintenance mode, then stop workers, queues, and cron on the old box. Stop the workers first so nothing writes while you serve the 503.
  3. T+5: run the final rsync with --delete-after. Only the deltas move, so it should take minutes.
  4. T+10: do the final dump and restore, or stop writes, confirm zero lag and promote the replica.
server {
    listen 443 ssl;
    server_name example.com;
    # ssl_certificate lines unchanged
    add_header Retry-After 600 always;
    return 503;
}

systemctl stop myapp-worker
systemctl mask --now backup.timer
rsync -aHAX --numeric-ids --delete-after -e ssh /var/www/ new:/var/www/

Switch DNS and watch both servers

  1. T+20: on the new server, run restorecon -Rv if SELinux is enforcing, start the services and run your smoke tests through curl --resolve.
  2. T+30, go/no-go: if any smoke test still fails, abort. Remove the 503, restart the workers and timers on the old box, and you are back. Nothing has been lost, because DNS has not moved.
  3. Unmask the timers and enable cron on the new server. Then change the A and AAAA records. A forgotten AAAA sends every IPv6 client to the old box.
  4. Run tail -f /var/log/nginx/access.log on both servers. Old traffic should drain over minutes. Some resolvers ignore TTL, so expect stragglers for hours.
  5. Optionally turn the old nginx into a forwarder so stragglers see current data:
location / {
    proxy_pass https://203.0.113.20;
    proxy_set_header Host $host;
    proxy_ssl_server_name on;
}

Never leave two writable copies. Once the old app accepts a write, you have a merge problem rather than a migration.

Rollback and decommissioning without regret

What a rollback needs to be possible

Rollback is free until the first write lands on the new server. After that it is a data-merge job, so decide the rule in advance: if you roll back after the DNS change, freeze the new app first, then move its changes back.

  • Dump the new database and import it over the old one, or at least export the rows created since cutover.
  • For files, reverse the rsync with source and destination swapped. Run it with -n first and be careful with --delete: pointed the wrong way, it removes the good copy.
  • Keep the old server stopped but intact: services down, data untouched, not destroyed.
  • Keep the TTL at 300 for 48 to 72 hours. Raise it only once things are stable, otherwise a late rollback is slow.

When it is safe to shut the old server down

Before you delete anything, check that the new server stands on its own:

  • Its own backups run, and a restore test into a scratch location passes.
  • certbot renew --dry-run succeeds (see the Certbot documentation).
  • Mail logs show clean delivery from the new IP.
  • Monitoring probes the new address, not just the hostname.

Take a final full backup or provider snapshot of the old server, and keep it for two to four weeks. Then delete it. Finally, remove the old IP from documentation, ~/.ssh/known_hosts, monitoring targets and every firewall allowlist.

Migration day checklist

Print this and tick items as you go. If a box stays unticked at the go/no-go point, that is your answer.

  • TTL lowered at least one full old TTL ago, on every moving record including AAAA.
  • Inventory file complete: services, cron, timers, users, mounts, hooks, allowlists.
  • New server has matching UIDs, packages, time sync and firewall rules.
  • First sync done, and a dry run of the final sync shows only small deltas.
  • Database restore timed on real data, row counts compared.
  • curl --resolve tests pass, including TLS, login and a write path.
  • Cron and timers masked on the new server until cutover.
  • Third parties have the new IP: SMTP relay, payment provider, database firewall.
  • PTR and SPF updated if the server sends mail.
  • Rollback rule written down, with the abort time agreed.
  • Old server kept stopped but intact after the switch.
  • Snapshot taken and a retention date set.

If you want the whole process in one place, including the awkward cases like mail and multi-site hosts, the Linux Server Migration Handbook follows the same runbook approach.

Frequently Asked Questions

How long before a server migration should I lower the DNS TTL?

At least one full old TTL before the cutover. If the record has a TTL of 86400, lower it to 300 at least 24 hours ahead, and 48 is safer. Resolvers that cached the old value keep it until it expires, so lowering it an hour before gains you nothing.

Can I rsync /var/lib/mysql or /var/lib/postgresql to the new server?

Not from a running database. The files change while rsync reads them, so the copy is inconsistent and often will not start. Use a logical dump with mysqldump or pg_dump, or replication. A file-level copy is only safe with the database fully stopped, and then only to the same major version.

Why does my Let's Encrypt certificate fail to renew after moving servers?

Usually DNS still points at the old server, so the HTTP-01 challenge lands there. Other causes: port 80 blocked on the new firewall, a missing webroot path, or a renewal config referencing a plugin or hook that was not installed. Run certbot renew --dry-run and read the error it prints.

Do I need to keep the old server running after DNS has changed?

Keep it for 48 to 72 hours, either serving a proxy to the new IP or stopped with data intact. That window covers resolvers that ignore TTL and gives you a rollback target. After that, take a snapshot, keep it a few weeks, then delete the server.

How do I keep file ownership correct when copying between servers with rsync?

Run rsync as root on the sending side and use -a --numeric-ids, so raw UIDs and GIDs are copied instead of names. Create users and groups on the target with the same numeric IDs first. Add -A -X for ACLs and extended attributes, and run restorecon where SELinux is enabled.

Share this article:
Dorian Thorne
About the Author

Dorian Thorne

Cloud Infrastructure, Cloud Architecture, Infrastructure Automation, Technical Documentation

Dorian Thorne is a cloud infrastructure specialist and technical author focused on the design, deployment, and operation of scalable cloud-based systems.

He has extensive experience working with cloud platforms and modern infrastructure practices, including virtualized environments, cloud networking, identity and acces...

Cloud Computing Cloud Networking Identity and Access Management Infrastructure as Code System Reliability

Stay Updated

Subscribe to our newsletter for the latest tutorials, tips, and exclusive offers.