VPS / Security
Secure an Ubuntu VPS: SSH, firewall, updates, backups
A risk-reduction checklist for Ubuntu VPS operation, with access checks that avoid lockout.
Secure an Ubuntu VPS by preserving recovery access first, then verifying a non-root administrator and SSH key, restricting SSH, enabling a firewall, maintaining updates, and testing independent backups. Keep your existing SSH session open throughout access changes. Require a successful second connection before removing any working login method. Treat each control as risk reduction, not proof of complete security: access restrictions, patching, least privilege, and recoverable data address different failure modes.
1. Establish recovery access before changing SSH
Start with a working recovery route outside normal SSH. Check your provider’s current documentation for console access, rescue boot, disk attachment, and account recovery. Availability and procedures vary; verify them for your VPS rather than assuming a dashboard button guarantees usable access.
- Sign in to your provider account and enable its available multifactor authentication.
- Open the console or confirm the documented recovery procedure.
- Identify any credentials needed when SSH keys cannot be used.
- Store recovery instructions and account recovery material somewhere accessible without this VPS.
- Keep your current SSH connection open until all access changes pass their checks.
Decide who can perform recovery if your usual administrator is unavailable. For a shared service, record an authorized alternate rather than sharing one person’s provider credentials.
Stop if recovery depends on an untested assumption. A firewall mistake is manageable when recovery works; without recovery, the same mistake can become a prolonged outage. Schedule access changes when someone can use the console, not immediately before leaving the server unattended.

2. Create and verify a non-root administrator
If your initial account is root, establish a named administrator before restricting root login. If provisioning already supplied a non-root account with working administrative access, verify it instead of creating another account.
On a conventional Ubuntu installation using the sudo group, create an account with sudo adduser opsadmin, then grant administration with sudo usermod -aG sudo opsadmin. Substitute your chosen account name. Run these commands from an existing administrative account; when already root, omit sudo.
- Open a separate SSH session as the new administrator using an available authentication method.
- Run
idto inspect group membership. - Run
sudo -vand confirm authentication succeeds. - Run
sudo whoami; expectroot. - Keep the original administrative session open.
Do not interpret successful login alone as successful administration. An account that cannot elevate privileges may be unable to repair SSH or firewall settings.
Use named accounts for people who administer the VPS. Keep routine application processes separate from those accounts. Review who genuinely needs unrestricted administration; do not grant it merely because an application needs access to one directory.
3. Verify SSH keys in a second session
Install your public key in the intended administrator account. Keep the private key on your client, not on the VPS. Ubuntu’s OpenSSH guidance covers key authentication, authorized keys, and permissions; follow its installation checks before disabling another login method. Ubuntu OpenSSH documentation
If ssh-copy-id is available on your client, use ssh-copy-id opsadmin@server-address. Specify the intended public-key file when your client has several identities. Confirm the destination account and server address before accepting any prompt.
Then test deliberately:
- Leave the original session open.
- Start a new connection using the intended key.
- Disable password fallback for that test, for example with
ssh -o PreferredAuthentications=publickey -o PasswordAuthentication=no opsadmin@server-address. - Confirm the expected account with
whoami. - Verify administrative access again with
sudo -v.
A normal successful connection may conceal password fallback. The explicit test establishes whether public-key authentication works independently.
If authentication fails, inspect the destination account, selected key, file ownership, permissions, and server authentication logs. Fix that path before proceeding. Do not weaken unrelated permissions or copy a private key onto the server to make login work.
4. Restrict SSH only after verification
Once key authentication and administration work, consider disabling direct root login and password-based SSH authentication. Inspect existing configuration and included snippets first; adding a contradictory setting elsewhere may not produce your intended result. Ubuntu documents SSH configuration, syntax testing, and service management. Ubuntu OpenSSH documentation
For a key-only setup, review PermitRootLogin no, PasswordAuthentication no, and KbdInteractiveAuthentication no. Do not disable keyboard-interactive authentication if your intended multifactor arrangement requires it. Keep the authentication methods your actual access design needs.
- Record existing settings and retain a recoverable copy.
- Make one coherent change.
- Run
sudo sshd -t. Correct every reported error before continuing. - Inspect effective configuration with
sudo sshd -T; account-specific rules need separate attention. - On a standard Ubuntu installation using
ssh.service, reload withsudo systemctl reload ssh. - Open another fresh connection and repeat login and
sudochecks.
Syntax validation does not prove that your key, account rules, and client settings work together.
If the fresh connection fails, revert through the session you preserved. Do not close that session or reboot while the access path remains unverified.
5. Enable a firewall without blocking SSH
Inventory required inbound connections before enabling filtering. Include SSH, public application traffic, monitoring, and any deliberately exposed management endpoint. UFW is Ubuntu’s documented host-firewall interface; its rules should reflect services you actually intend to expose. Ubuntu firewall documentation
For a VPS without an existing firewall policy:
- Inspect current state with
sudo ufw status verbose. - Identify the actual SSH port and any upstream provider firewall.
- Set the intended baseline, commonly
sudo ufw default deny incomingandsudo ufw default allow outgoing. - Allow the actual SSH port before enabling UFW. For SSH on TCP port 22, use
sudo ufw allow 22/tcp. - Add required application rules.
- Run
sudo ufw enable, then inspect status again. - Test a fresh SSH connection and each public service externally.
Do not copy the port-22 rule if SSH listens elsewhere. On an already managed server, reconcile existing rules rather than replacing policy blindly.
Restrict SSH to trusted source networks when practical. For changing home addresses, document how rules will be updated through verified recovery access. Apply equivalent intent to IPv4 and IPv6 wherever both are enabled.
6. Check Docker exposure separately
Do not assume UFW blocks every container port. Docker documents that published container traffic can be diverted before the UFW chains normally used for host filtering, bypassing expected UFW restrictions. Docker also creates networking rules needed for its own operation. Docker firewall documentation
Review container port mappings alongside host listeners. Distinguish an application intended for public use from a database or internal administration endpoint. Remove unnecessary publication rather than adding layers of filtering around an endpoint nobody needs.
Hypothetical example: A website uses a containerized database. The web application needs database access, but internet clients do not. Keep database communication within the intended private container network instead of publishing its port on every host interface.
For a service needed only by a host-side proxy, consider publishing it to loopback rather than all interfaces. Then verify reachability from another machine; local connection tests cannot establish external isolation.
Do not disable Docker’s firewall-rule management as a quick fix. Docker warns that changing this behavior can break container networking. Select filtering guidance matching your Docker version and firewall backend rather than mixing instructions for different backends. Docker firewall guidance
7. Make updates a maintained process
Use Ubuntu’s package tools rather than manual replacement of packaged system components. sudo apt update refreshes package information; apt list --upgradable shows available upgrades; sudo apt upgrade applies an ordinary upgrade after you review the proposed changes. Ubuntu documents these operations and automatic-update tooling. Ubuntu package-management documentation
Before updating an important VPS, confirm recent backup availability and recovery access. Review removals or unexpected dependency changes instead of accepting them reflexively. Avoid unattended use of confirmation flags during unfamiliar maintenance.
Choose how automatic updates fit your operation. Ubuntu provides unattended-upgrades; verify its configuration, permitted origins, and reporting rather than assuming every installed component is covered. Applications installed outside Ubuntu package repositories need their own maintenance plan. Ubuntu package-management documentation
Set a reboot decision explicitly. Where /var/run/reboot-required is present, schedule a controlled reboot and check service recovery afterward. Do not configure automatic reboots without deciding which outages are acceptable.
If an update fails, preserve its error output, inspect package state, and investigate before retrying repeatedly. Confirm application health after successful package installation; a completed package command is not an application-level acceptance test.
8. Reduce privileges and protect secrets
Separate administration, application execution, and deployment wherever their needs differ. Give application accounts access to required files, not unrestricted write access across the host. Avoid running an application as root merely to bypass an ownership error.
Review administrative access before removing it. Use sudo visudo when editing sudo policy, and keep a verified administrative session available. Broad passwordless privileges should require an explicit operational reason, not convenience alone.
For secrets, make an inventory: database passwords, API credentials, deployment keys, backup credentials, and provider tokens. Record where each is stored, which process reads it, and how it can be replaced.
Keep secrets out of source control, public web directories, copied support output, and shell commands that may be retained in history. Restrict secret files to the accounts that need them. Check deployment scripts and backups too; moving credentials out of application code does not remove older copies.
Hypothetical example: A deployment task needs to update one application directory. Prefer scoped ownership and a narrowly defined privileged operation over granting its account unrestricted administration. Test deployment and rollback with those permissions before removing the previous access path.
9. Make logs useful before an incident
Decide which questions your logs must answer: who attempted access, whether updates failed, why an application stopped, and whether backups completed. Collect enough evidence to answer those questions without recording credentials or unnecessary personal data.
On installations using systemd’s journal, sudo journalctl -u ssh --since today provides a starting point for SSH service records. Confirm the actual service name and logging arrangement on your VPS. Ubuntu’s SSH documentation also describes troubleshooting through service logs. Ubuntu OpenSSH documentation
Inspect representative records before relying on alerts. Confirm timestamps make sense, expected events appear, and someone receives notifications outside the server. A notification delivered only to a mailbox hosted on the failing VPS is a weak recovery signal.
Set retention and storage limits deliberately. Check free disk space and confirm logs remain available long enough for your investigation needs. If retaining logs off-host, test delivery during normal operation.
Alert on actionable conditions: repeated backup failures, unavailable public services, exhausted storage, and unexpected administrative changes. Define an owner and response for each alert. Notifications nobody can interpret or act on add noise without improving recovery.
10. Back up data with usable consistency
Define recovery requirements before choosing a backup schedule. Decide how much recent work you can lose and how long restoration may take. Those decisions determine backup frequency, retained history, and whether a replacement VPS must be prepared in advance.
Inventory application data, database contents, uploaded files, system configuration, service definitions, and required secrets. Record installation and restore steps separately. A backup containing files without their dependencies may leave you unable to recreate the service.
For databases, choose a database-supported export or backup procedure that produces a consistent recovery point. Do not assume copying live database files is sufficient. Coordinate related application files where their state must match database records.
Keep at least one recovery copy outside this VPS’s failure and credential boundary. Verify your provider’s current snapshot and backup terms before relying on retention, deletion protection, or restore behavior. Do not treat unspecified provider features as established guarantees.
Protect backup credentials and decryption material separately enough that one compromised application cannot readily destroy every recovery option.
Match restore capacity to your workload using the VPS sizing guide. Include room for restored data and temporary recovery work, not only normal runtime use.

11. Run restore drills and prepare incident actions
Test restoration onto an isolated replacement environment, not over your only working service. Record the backup selected, required credentials, missing dependencies, and elapsed recovery time. Treat those results as observations for your environment, not universal performance promises.
During a drill:
- Restore configuration, data, and required secrets.
- Keep public traffic disconnected.
- Disable outbound mail, scheduled jobs, payments, and integrations that could duplicate real actions.
- Verify representative reads, writes, authentication, and uploads.
- Document traffic-switch and rollback steps.
- Remove temporary access and securely handle restored sensitive data.
For a web move, coordinate these checks with your migration procedure.
Prepare incident decisions separately. For suspected compromise, use a trusted device to access the provider account, preserve relevant logs and timestamps, and contain affected services through verified controls. Prioritize stopping active harm without destroying evidence unnecessarily.
Rotate potentially exposed credentials from a trusted environment. Do not assume deleting an unfamiliar process restores trust. Plan replacement from a known-good installation, restore selected data carefully, and fix the suspected entry path before reconnecting public traffic. Seek qualified incident support when sensitive data or reporting obligations are involved.
12. Keep a recurring checklist with stop conditions
Turn hardening into small, owned checks rather than a one-time session. Assign responsibility and record exceptions with a review date. Choose frequency based on service exposure and recovery needs.
| Cadence | Check | Required follow-up |
|---|---|---|
| After access changes | Fresh SSH login, intended key, working sudo |
Revert before closing recovery session if checks fail |
| After network changes | External reachability for intended services; Docker mappings | Remove unintended exposure and retest |
| After updates | Package outcome, service health, reboot need | Resolve failures and schedule remaining work |
| At backup frequency | Successful backup and usable recovery credentials | Investigate missed recovery points |
| Periodically | Isolated restore, accounts, keys, firewall rules | Remove obsolete access and fix restore gaps |
Recheck recovery access after provider-account changes. Recheck secrets after staff departures or deployment changes. Recheck listening services when adding software, not only when editing firewall rules.
Keep stop conditions explicit: no verified key means no password-login removal; no working recovery route means no risky access change; no successful restore means backups remain unproven.
When checks fail, reduce the change’s scope and repair the failed prerequisite. Preserve working access while doing so. Progress means fewer untested assumptions, not more settings changed in one maintenance window.