Dev guide :: VPS Deployment

VPS Deployment: from a new server to running apps

Build a small application server step by step: AlmaLinux 10, SSH, firewalld, Docker Compose, Traefik, a landing page, and app1, a Vue/Vite application. A final exercise adds app2.

1. Before you start

1.1 Check the prerequisites and placeholders

Have console access, your IP address and your domain ready before changing the server.

You need a VPS provisioned with AlmaLinux 10, its public IPv4 address, provider console access, initial administrative credentials, and a domain whose DNS you can edit. Use an empty server: these instructions create configuration files and are not a migration procedure. Keep the provider rescue console available in case SSH stops working.

Use a terminal on your computer: PowerShell on Windows, Terminal on macOS, or a Linux shell. Commands marked PC run locally; commands marked VPS run after connecting by SSH. VPS commands use Bash. Copy commands without a prompt character. sudo runs one command with administrator privileges; its password prompt displays no characters.

Replace VPS_IP with your real public IPv4 address everywhere. Replace example.com with your own domain, admin@example.com with your email, and YOUR_GITHUB_USER with your GitHub account. example.com and the sample IP are documentation values: they cannot issue certificates for you. Keep names deploy, app1, landing, proxy and /srv unchanged while learning.

1.2 Understand the tools and their roles

Learn which component builds, runs, routes and protects your applications.

A Docker image is a ready-to-use package containing an application, the files it needs, and instructions for starting it. For example, the Nginx image contains a web server: software that answers browser requests with web pages. Later, you will build an app1 image containing Nginx and your compiled Vue files. Downloading or building an image does not start the application.

A container is an instance created from an image. Starting the container runs its application in an isolated environment on the VPS. Think of the image as a saved template and the container as a working copy: one image can create several containers. Containers can be started, stopped and replaced. Keep important changing data in persistent storage, such as a Docker volume, so replacing a container does not discard it.

Docker Compose is the tool that reads a compose.yaml file and creates the containers described there. YAML is a text format that uses indentation to organize settings. Instead of typing a long Docker command each time, you record each service’s image, networks, storage and restart settings in this file. In this guide, a service means a named application component, such as web or traefik. Running docker compose up -d starts the project in the background.

A hostname is a readable address such as app1.example.com. DNS is the lookup system that lets your browser find the IP address for that name. You will create DNS A records pointing your domain and app hostnames to your VPS IPv4 address. Several names can point to the same server; DNS alone does not choose which container should answer.

A port is a numbered connection point on a machine, like a particular entrance to a building. HTTP normally uses TCP port 80, HTTPS uses 443, and SSH uses 22. Containers also have their own ports. Publishing a container port connects it to a port on the VPS, potentially making it reachable from outside. Here, only Traefik publishes web ports; each Nginx app listens on port 80 inside its own container.

A reverse proxy is the shared front door for your websites. In this guide, Traefik receives browser requests on the VPS and uses the requested hostname to choose an application. A request for example.com goes to landing, while app1.example.com goes to app1, even though both names point to the same IP. Traefik forwards the request to that app’s internal port and sends its response back to the browser.

TLS is the security protocol used by HTTPS. It encrypts the connection between the browser and Traefik, and a certificate lets the browser check that it is talking to a server authorized for the requested hostname. Traefik will obtain and renew certificates from Let’s Encrypt. In this setup, TLS ends at Traefik: the separate connection from Traefik to Nginx uses HTTP over a Docker network.

A Docker network connects containers so they can contact each other using internal addresses and service names. You will create a network named proxy and connect Traefik and the web apps to it. This lets Traefik reach app1’s port 80 without publishing a separate app1 port on the VPS. Containers on the same network can communicate, so the Docker socket proxy and any future database need separate networks with only the components that require access.

1.3 See the server you will build

Use this topology to locate the public entry point and the containers behind it.

flowchart LR
    PC[Your computer] -->|SSH TCP 22| Host[AlmaLinux VPS]
    Browser[Browser] -->|DNS lookup| DNS[DNS provider]
    Browser -->|HTTP 80 or HTTPS 443| T[Traefik]
    subgraph VPS[Application server]
        Host
        T -->|HTTP on proxy network| L[landing: Nginx]
        T -->|HTTP on proxy network| A[app1: Vue built into Nginx]
        T -->|HTTP on proxy network| B[app2: Nginx]
        T -->|Discovery on private docker-api network| S[Socket proxy]
        S -->|Restricted Docker API requests| D[Docker daemon]
    end

1.4 Follow the setup order

Complete each checkpoint before moving to the next stage in this sequence.

flowchart TD
    A[Provision and connect] --> B[Create deploy and test SSH key]
    B --> C[Harden SSH and enable firewall]
    C --> D[Install Docker and create networks]
    D --> E[Configure DNS and Traefik]
    E --> F[Verify landing page and HTTPS]
    F --> G[Build and deploy app1]
    G --> H[Add app2 and rehearse recovery]
    H --> I[Back up and monitor]

2. Provision, connect, and update

2.1 Create the VPS and connect by SSH

Obtain a working remote administrator session and keep a console recovery path.

In the provider dashboard, create an AlmaLinux 10 VPS and record its public IP. Enable the provider firewall for inbound TCP 22, 80 and 443; restrict 22 to your public IP if practical. Allow outbound DNS and HTTPS. Enable console access before changing SSH. The provider firewall and the operating system firewall are separate controls.

bash
ssh root@VPS_IP

PC: ssh opens an encrypted session as root. If your provider supplies a different administrative user, use that name instead and prefix administrative commands in this section with sudo. Compare the SSH host fingerprint with the provider console before accepting the first connection. Expected: a remote shell prompt. A timeout usually means a wrong IP or blocked port; permission denied means the username, password or key is wrong.

2.2 Verify the OS and current account

Confirm you are on the intended AlmaLinux 10 server before making changes.

VPS, initial administrator: run one command at a time. If your provider supplied a non-root administrator, prefix each administrative dnf/reboot command below with sudo.

bash
cat /etc/os-release

Read the operating-system identity. Expected: AlmaLinux with VERSION_ID starting with 10. Stop if a different OS or major version is installed.

bash
whoami

Check which account owns this SSH session. Expected: root, or the administrative username supplied by your provider.

2.3 Install updates and required tools

Prepare the operating system and utilities used throughout the tutorial.

bash
dnf upgrade --refresh -y

Refresh package metadata and update installed packages. --refresh requests fresh repository data; -y accepts transaction prompts. Expected: a completed transaction or nothing to do. Resolve errors before continuing.

bash
dnf install -y sudo nano git curl bind-utils firewalld python3 policycoreutils

Install the tools used by this tutorial: administrator access, editor, Git, HTTP/DNS tools, firewall, Python and SELinux utilities. Expected: installation completes, possibly reporting some packages already installed.

2.4 Reboot and reconnect

Load the updated system and prove the VPS is reachable again.

bash
reboot

Restart the VPS to load the updated system. Expected: SSH disconnects. Wait for the server to boot, then reconnect from your PC with the same SSH command before starting the next section.

3. Create deploy and prove key access

3.1 Create the deploy user

Create your everyday administration account and grant it sudo access.

VPS, initial administrator: keep this session open while preparing deploy.

bash
sudo useradd -m -s /bin/bash deploy

Create deploy with a home directory (-m) and Bash as its login shell (-s). Expected: no output on success and a new /home/deploy directory. If the account already exists, inspect it rather than recreating it.

bash
sudo passwd deploy

Set a strong password for deploy, entering it twice when prompted. No characters appear while typing. Expected: confirmation that the password was updated. Keep it securely: deploy will use it for sudo.

bash
sudo usermod -aG wheel deploy

Append deploy to the wheel administrator group. -a preserves existing memberships; -G selects the additional group. Expected: no output on success. A new login session will receive this membership.

bash
id deploy

Display deploy’s account and group IDs. Expected: the output includes deploy and wheel. If wheel is absent, stop and fix the group membership.

bash
sudo visudo -c

Check sudo configuration syntax without editing it. Expected: parsed OK for the configuration files. Wheel normally grants sudo on AlmaLinux; the later sudo whoami test verifies the actual permission.

3.2 Create an SSH key on your PC

Generate the key pair that will authenticate you to the VPS as deploy.

bash
ssh-keygen -t ed25519 -f vps_deploy -C "deploy-vps"

PC, in your home directory: ssh-keygen creates the private file vps_deploy and public file vps_deploy.pub. Choose a passphrase and do not overwrite an existing key. Keep the private file on your PC; only the .pub file belongs on the server. On Windows run Get-Content ./vps_deploy.pub; on macOS/Linux run cat ./vps_deploy.pub. Expected: one line starting ssh-ed25519. Copy the entire line.

3.3 Authorize the public key on the VPS

Install only the public key in deploy’s account and protect its SSH files.

VPS, initial administrator: install only the public login key copied from your PC.

bash
sudo install -d -m 700 -o deploy -g deploy /home/deploy/.ssh

Create deploy’s SSH directory. -d creates a directory, -m 700 restricts access to its owner, and -o/-g assign deploy ownership. Expected: no output on success.

bash
sudo nano /home/deploy/.ssh/authorized_keys

Paste the entire public key from your PC into this file as one line. Save with Ctrl+O, Enter, then exit with Ctrl+X. Expected: authorized_keys contains the line starting ssh-ed25519, never your private key.

bash
sudo chown deploy:deploy /home/deploy/.ssh/authorized_keys

Assign the authorized-key file to deploy and its primary group. Expected: no output on success; root no longer owns this newly created file.

bash
sudo chmod 600 /home/deploy/.ssh/authorized_keys

Permit only deploy to read and write its authorized-key file. Expected: no output on success. Restrictive permissions prevent SSH from rejecting an insecure key file.

bash
sudo restorecon -Rv /home/deploy/.ssh

Restore the expected SELinux labels recursively (-R); -v reports changes if needed. Expected: relabeling messages or no output when labels are already correct. Keep the original administrator session open.

3.4 Test deploy login and sudo

Prove the new account works in a separate session before restricting existing access.

Use two terminals carefully: start the SSH command on the PC, then run the administrator test inside the new VPS session.

bash
ssh -i ./vps_deploy -o PreferredAuthentications=publickey -o PasswordAuthentication=no deploy@VPS_IP

PC, second terminal in the folder containing vps_deploy: connect as deploy using this private key (-i). The options require key authentication without a server-password fallback. Expected: a remote deploy prompt; a private-key passphrase prompt is normal.

bash
sudo whoami

Now in that new VPS session, enter deploy’s password to test administrator access. Expected: root. If login or this test fails, repair it from the original session before hardening SSH. All later VPS commands use deploy with sudo where shown.

flowchart TD
    K[Install public key] --> T[Test deploy key in second terminal]
    T --> Q{Login and sudo both work?}
    Q -->|No| F[Repair using original session or provider console]
    F --> T
    Q -->|Yes| H[Disable root and password SSH]
    H --> V[Validate and reload]
    V --> R[Test a third connection before closing old sessions]

4. Harden SSH and configure the firewall

4.1 Disable root and password SSH login

Require the key-based deploy access you have just tested.

bash
sudo nano /etc/ssh/sshd_config.d/00-deploy.conf

VPS, deploy: create this drop-in and save the following content. The early filename helps these settings precede other drop-ins; OpenSSH usually takes the first value encountered. Provider settings or Match blocks can still affect the result, so check the effective configuration rather than assuming the file wins.

plaintext
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes

PermitRootLogin blocks remote root login; PasswordAuthentication and KbdInteractiveAuthentication disable password-style SSH authentication; PubkeyAuthentication keeps keys enabled. The deploy password still works for sudo. These settings apply to SSH, not to the provider console.

4.2 Validate, reload, and retest SSH

Apply the policy only after checking it, while keeping an existing session available.

VPS, deploy: validate SSH before reloading it. Stop after any failed check.

bash
sudo sshd -t

Validate SSH configuration syntax before applying it. Expected: no output on success. If an error appears, fix the file and repeat this command; do not reload a broken configuration.

bash
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication) '

Display effective SSH settings (-T), then filter them with grep. Expected: permitrootlogin no, passwordauthentication no, kbdinteractiveauthentication no, pubkeyauthentication yes, in any order. Investigate conflicting includes and Match rules for deploy before continuing.

bash
sudo systemctl reload sshd

Apply the validated SSH configuration without closing established sessions. Expected: no output on success. Test key-only deploy login in a third PC terminal; keep a working session open until the new login succeeds.

4.3 Start firewalld and identify the public zone

Find the actual interface and zone to which the next firewall rules must apply.

VPS, deploy: identify the public interface’s active firewall zone before adding exceptions.

bash
sudo systemctl enable --now firewalld

Start firewalld now and enable it at boot. Expected: no error; systemd may report creating an enablement symlink. Resolve startup errors before proceeding.

bash
sudo firewall-cmd --get-active-zones

List active firewall zones and their interfaces. Expected: a zone attached to the public interface. Note its name; later examples use public, which you must replace if your active zone differs.

bash
ip route show default

Find the interface used for the default outbound route: its name follows dev. Match it to the firewall zone above. Expected: a default route through your public interface. Do not move a live interface blindly; use the provider console if SSH becomes unreachable.

4.4 Allow SSH and web traffic

Keep administration reachable and open the two ports Traefik will use.

VPS, deploy: replace public with the active zone identified above if necessary.

bash
sudo firewall-cmd --permanent --zone=public --add-service=ssh

Save the ssh exception for TCP 22 in the selected zone. --permanent stores it for future reloads; it is not active yet. Expected: success or an already-enabled warning. Replace public if your interface uses another zone.

bash
sudo firewall-cmd --permanent --zone=public --add-service=http

Save the http exception for TCP 80 in the selected zone. --permanent stores it for future reloads; it is not active yet. Expected: success or an already-enabled warning. Replace public if your interface uses another zone.

bash
sudo firewall-cmd --permanent --zone=public --add-service=https

Save the https exception for TCP 443 in the selected zone. --permanent stores it for future reloads; it is not active yet. Expected: success or an already-enabled warning. Replace public if your interface uses another zone.

bash
sudo firewall-cmd --permanent --zone=public --remove-service=cockpit

Remove the permanent exception for Cockpit web administration. Expected: success, or a warning if the exception is already absent. This changes the firewall rule, not the installed package.

bash
sudo firewall-cmd --reload

Load permanent firewall rules into the active configuration. Expected: success. This is when the newly saved service exceptions become active; retest SSH before closing existing sessions.

bash
sudo firewall-cmd --zone=public --list-all

Inspect the active public-zone rules. Expected: services include ssh http https without cockpit. Also inspect ports and other exceptions supplied by the provider. Check its separate firewall too; Docker published ports have their own forwarding rules, so never rely solely on firewalld to hide a database.

5. Install and test Docker Compose

5.1 Add the Docker repository and install packages

Install the engine and Compose plugin from the official AlmaLinux repository.

VPS, deploy, any directory: install and verify Docker in this order.

bash
sudo dnf install -y dnf-plugins-core

Install the DNF plugins that provide config-manager. -y accepts package prompts. Expected: a successful transaction or a message that the package is already installed.

bash
sudo dnf config-manager --add-repo https://download.docker.com/linux/alma/docker-ce.repo

Add Docker’s official AlmaLinux repository from this HTTPS URL. Expected: confirmation that the repository definition was added. Stop if the download or repository setup fails.

bash
sudo dnf install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Install the Docker engine, command-line client, container runtime, Buildx builder and Compose plugin. Verify the signing-key fingerprint using Docker’s official installation reference before accepting it. Expected: a completed package transaction.

5.2 Start Docker and run a test container

Verify the daemon, client and Compose work before deploying real services.

bash
sudo systemctl enable --now docker

Start docker now and enable it at boot. Expected: no error; systemd may report creating an enablement symlink. Resolve startup errors before proceeding.

bash
sudo docker version

Ask both the Docker client and daemon for their versions. Expected: Client and Server sections. A daemon connection error means Docker is not running or accessible; fix that before proceeding.

bash
sudo docker compose version

Check that the Compose plugin is available. Expected: Docker Compose version followed by a version number. A missing command means the plugin installation needs fixing.

bash
sudo docker run --rm hello-world

Download and run Docker’s test image. Expected: Hello from Docker! followed by an explanation. --rm removes the test container after it exits; the downloaded image stays cached.

Keep sudo for Docker commands. Membership in the docker group is effectively administrator access. Never make the Docker socket world-writable or expose its API port publicly. If a package transaction fails, stop and consult the AlmaLinux installation reference linked at the end rather than switching repositories at random.

5.3 Configure log rotation and live restore

Set bounded container logs before creating the application containers.

bash
sudo nano /etc/docker/daemon.json

On this fresh server create daemon.json with the following JSON. If it already exists, merge the keys carefully rather than overwriting it. log-driver local enables bounded local logs; max-size and max-file rotate each container’s logs. live-restore can keep containers running through some daemon interruptions; it is not high availability.

json
{
  "log-driver": "local",
  "log-opts": { "max-size": "10m", "max-file": "3" },
  "live-restore": true
}

5.4 Validate and apply the daemon settings

Check the configuration before restarting and verify the effective settings afterward.

VPS, deploy: validate both syntax and daemon options before restarting Docker.

bash
sudo python3 -m json.tool /etc/docker/daemon.json

Check the JSON syntax and print the formatted configuration. Expected: valid formatted JSON. If parsing fails, correct the file before restarting Docker.

bash
sudo dockerd --validate --config-file=/etc/docker/daemon.json

Check that Docker accepts the daemon options, not just the JSON syntax. Expected: configuration OK. Do not restart the daemon if validation fails.

bash
sudo systemctl restart docker

Restart Docker to apply the validated daemon settings before any apps are deployed. Expected: no output on success. The next command verifies that it started again.

bash
sudo systemctl is-active docker

Check the Docker systemd service state. Expected: active. If it reports failed or inactive, investigate before running containers.

bash
sudo docker info --format '{{.LoggingDriver}} {{.LiveRestoreEnabled}}'

Print the effective logging driver and live-restore setting using Docker’s output template. Expected: local true. Logging defaults apply to newly created containers, not automatically to old ones.

6. Prepare directories, networking, and DNS

6.1 Create the infrastructure and app directories

Give each deployment a predictable location owned by deploy.

VPS, deploy: prepare the shared directory layout and network.

bash
sudo install -d -o deploy -g deploy /srv/infra/traefik /srv/apps/landing /srv/apps/app1 /srv/apps/app2

Create the infrastructure and application directories with deploy ownership. -d creates directories and -o/-g set owner/group without recursively changing unrelated files. Expected: no output on success.

6.2 Create the shared proxy network

Let independently managed web applications communicate with Traefik.

bash
sudo docker network create proxy

Create the shared Docker network once. Expected: a network ID. If proxy already exists, inspect it with the next command instead of recreating it. As an external Compose network, it is shared across projects and survives compose down.

bash
sudo docker network inspect proxy --format '{{.Name}}'

Inspect the existing network and print its name. Expected: proxy. A not-found error means network creation did not succeed.

bash
cd /srv/infra/traefik

Change the current terminal’s working directory to /srv/infra/traefik. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
pwd

Print the current working directory. Expected here: /srv/infra/traefik. Future relative file paths in this part of the guide are resolved from this directory.

flowchart TD
    SRV["/srv"] --> INF[infra]
    SRV --> APPS[apps]
    INF --> T[traefik]
    T --> C[compose.yaml and .env]
    T --> CFG[traefik.yaml]
    T --> ACME[letsencrypt/acme.json]
    APPS --> L[landing: compose.yaml and html/index.html]
    APPS --> A[app1: Git checkout, Dockerfile and compose.yaml]
    APPS --> B[app2: compose.yaml and html/index.html]

6.3 Point the domain and app hostnames to the VPS

Create the DNS records that browsers and certificate checks will resolve.

At your DNS provider create A records for example.com, app1.example.com and app2.example.com, all pointing to VPS_IP. Use DNS-only mode while learning so requests reach Traefik directly. Do not add AAAA records unless IPv6 routes and firewalls are configured; remove stale AAAA records. Record propagation can take the previous TTL. No www record is needed in this tutorial.

6.4 Verify the DNS answers

Confirm every public name resolves correctly before starting certificate issuance.

VPS, deploy, any directory: replace example.com with your domain in each DNS query.

bash
dig +short A example.com

Query the A DNS record for example.com; +short prints answers without the full DNS response. Expected: your VPS IPv4 address.

bash
dig +short A app1.example.com

Query the A DNS record for app1.example.com; +short prints answers without the full DNS response. Expected: your VPS IPv4 address.

bash
dig +short A app2.example.com

Query the A DNS record for app2.example.com; +short prints answers without the full DNS response. Expected: your VPS IPv4 address.

bash
dig +short AAAA example.com

Query the AAAA DNS record for example.com; +short prints answers without the full DNS response. Expected: no output for this IPv4-only setup. Repeat for app1 and app2. Remove stale IPv6 records; do not request certificates until all hostname records are correct. Check from your PC or another resolver if answers disagree.

sequenceDiagram
    participant U as Browser
    participant DNS as DNS resolver
    participant T as Traefik on VPS
    participant A as app1 container
    U->>DNS: Resolve app1.example.com
    DNS-->>U: VPS public IP
    U->>T: HTTPS 443, Host app1.example.com
    T->>A: HTTP port 80 over proxy
    A-->>T: HTML, JavaScript, CSS
    T-->>U: Encrypted HTTPS response

7. Configure Traefik and restricted discovery

7.1 Understand traffic and discovery isolation

Distinguish public app requests from the private Docker API discovery path.

Traefik owns public ports 80 and 443. Its Docker provider reads container labels through a socket proxy on an isolated network. Applications share proxy with Traefik but cannot directly reach the socket proxy. The socket proxy is still a sensitive component: mounting docker.sock read-only does not itself make API operations read-only; its request filtering and network isolation matter.

flowchart LR
    Internet -->|Published TCP 80 and 443| T[Traefik]
    subgraph proxy[Shared proxy network]
        T -->|Application HTTP| L[landing]
        T -->|Application HTTP| A[app1]
        T -->|Application HTTP| B[app2]
    end
    subgraph API[Private internal docker-api network]
        T -->|Allowed discovery GET requests| S[Socket proxy: no published ports]
    end
    S -->|Unix socket| D[Docker daemon]
    S -.->|POST requests denied| X[Write operations blocked]

7.2 Download and pin the infrastructure images

Record immutable image references so later starts use the versions you selected.

VPS, deploy: collect the three immutable image references before editing .env.

bash
cd /srv/infra/traefik

Change the current terminal’s working directory to /srv/infra/traefik. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
sudo docker pull traefik:v3

Download traefik:v3 into Docker’s local image cache. Expected: pull progress and a downloaded/up-to-date message. This does not start a container. Review release notes before selecting future image versions.

bash
sudo docker pull tecnativa/docker-socket-proxy:latest

Download tecnativa/docker-socket-proxy:latest into Docker’s local image cache. Expected: pull progress and a downloaded/up-to-date message. This does not start a container. Review release notes before selecting future image versions.

bash
sudo docker pull nginx:stable-alpine

Download nginx:stable-alpine into Docker’s local image cache. Expected: pull progress and a downloaded/up-to-date message. This does not start a container. Review release notes before selecting future image versions.

bash
sudo docker image inspect traefik:v3 --format '{{index .RepoDigests 0}}'

Read the immutable repository digest of traefik:v3. Expected: a complete image reference containing @sha256: and 64 hexadecimal characters. Save this entire output for TRAEFIK_IMAGE in .env, not just the hash; moving tags alone do not pin an image.

bash
sudo docker image inspect tecnativa/docker-socket-proxy:latest --format '{{index .RepoDigests 0}}'

Read the immutable repository digest of tecnativa/docker-socket-proxy:latest. Expected: a complete image reference containing @sha256: and 64 hexadecimal characters. Save this entire output for SOCKET_PROXY_IMAGE in .env, not just the hash; moving tags alone do not pin an image.

bash
sudo docker image inspect nginx:stable-alpine --format '{{index .RepoDigests 0}}'

Read the immutable repository digest of nginx:stable-alpine. Expected: a complete image reference containing @sha256: and 64 hexadecimal characters. Save this entire output for NGINX_IMAGE in .env, not just the hash; moving tags alone do not pin an image.

bash
nano .env

Open the infrastructure .env file. Paste the following template and replace each placeholder with the complete digest saved above. Save with Ctrl+O, Enter; exit with Ctrl+X. Expected: all three image variables are defined. This file supplies Compose interpolation values.

plaintext
TRAEFIK_IMAGE=traefik@sha256:PASTE_TRAEFIK_DIGEST
SOCKET_PROXY_IMAGE=tecnativa/docker-socket-proxy@sha256:PASTE_PROXY_DIGEST
NGINX_IMAGE=nginx@sha256:PASTE_NGINX_DIGEST

7.3 Prepare private certificate storage

Preserve ACME account and certificate state across container replacements.

VPS, deploy, /srv/infra/traefik: prepare certificate storage before saving Traefik configuration.

bash
mkdir -p letsencrypt

Create letsencrypt if it is missing. -p also creates missing parent directories and accepts an existing directory. Expected: no output on success; existing files are retained.

bash
touch letsencrypt/acme.json

Create the initially empty certificate-state file if absent. touch preserves existing content. Expected: no output; never empty or delete a working acme.json to repeat this tutorial.

bash
chmod 600 letsencrypt/acme.json

Restrict certificate-account and private-key storage to its owner. Expected: no output. Keep this private file out of public repositories.

7.4 Configure routing discovery and HTTPS

Tell Traefik where to listen, how to discover apps and how to obtain certificates.

bash
nano traefik.yaml

Create the Traefik configuration using the complete YAML below. Replace admin@example.com with your email, then save and exit nano. Expected: traefik.yaml is saved in /srv/infra/traefik. Keep configuration and ACME state out of public repositories.

yaml
entryPoints:
  web:
    address: ":80"
    http:
      redirections:
        entryPoint:
          to: websecure
          scheme: https
  websecure:
    address: ":443"
providers:
  docker:
    endpoint: "tcp://socket-proxy:2375"
    exposedByDefault: false
    network: proxy
certificatesResolvers:
  letsencrypt:
    acme:
      email: admin@example.com
      storage: /letsencrypt/acme.json
      httpChallenge:
        entryPoint: web
log:
  level: INFO
accessLog: {}

entryPoints defines HTTP and HTTPS listeners; the web redirect sends normal HTTP traffic to HTTPS. providers.docker uses the private proxy and exposedByDefault false requires an explicit label on each public app. network selects the shared network. The letsencrypt resolver obtains and renews certificates using HTTP-01 on port 80 and stores them in acme.json. log and accessLog enable operational and request logs. No dashboard or administrative port is exposed.

7.5 Define the Traefik and socket-proxy stack

Connect the containers to the required networks and publish only Traefik’s web ports.

bash
nano compose.yaml

Still in /srv/infra/traefik, save the complete Compose file below. YAML indentation uses spaces, not tabs. Compose substitutes the required image values from .env and stops if a variable is missing.

yaml
name: infra
services:
  socket-proxy:
    image: ${SOCKET_PROXY_IMAGE:?Set SOCKET_PROXY_IMAGE in .env}
    restart: unless-stopped
    security_opt:
      - label=disable
    environment:
      CONTAINERS: "1"
      NETWORKS: "1"
      EVENTS: "1"
      PING: "1"
      VERSION: "1"
      POST: "0"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - docker-api
  traefik:
    image: ${TRAEFIK_IMAGE:?Set TRAEFIK_IMAGE in .env}
    restart: unless-stopped
    depends_on:
      - socket-proxy
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./traefik.yaml:/etc/traefik/traefik.yaml:ro,Z
      - ./letsencrypt:/letsencrypt:Z
    networks:
      - proxy
      - docker-api
networks:
  proxy:
    external: true
  docker-api:
    internal: true

name fixes the project name to infra. restart restarts stopped processes except deliberately stopped containers; it does not repair unhealthy apps. depends_on orders startup but does not prove readiness. Only Traefik has ports. The proxy environment allows selected discovery API paths and denies POST writes. Internal docker-api isolates discovery from apps. The :ro mounts are read-only; :Z applies a private SELinux label to these dedicated configuration directories. Do not relabel the system Docker socket with :Z or disable SELinux.

security_opt label=disable disables SELinux label confinement only for the socket-proxy container so it can access the system Docker socket on AlmaLinux. SELinux stays enforcing for the host and the other containers. This is a deliberate exception for a trusted socket-facing component, not permission to run applications privileged. A custom SELinux policy is a more restrictive advanced alternative.

7.6 Start and inspect the infrastructure

Verify startup, discovery logs and socket-proxy isolation before adding apps.

VPS, deploy, /srv/infra/traefik: validate, start, then inspect the infrastructure.

bash
sudo docker compose config -q

Validate this project’s Compose structure and variable substitution. -q suppresses normal output. Expected: no output and a successful exit. Stop on any error; this does not validate every application configuration file.

bash
sudo docker compose up -d

Create or update this Compose project’s containers and run them in the background (-d). Expected: creation/start messages without errors. The next status check confirms they remain running; startup alone does not prove the site works.

bash
sudo docker compose ps

List this project’s containers, states and port mappings. Expected: both infrastructure services Up, with only Traefik publishing 80/443. Investigate exited, restarting or unhealthy states before proceeding.

bash
sudo docker compose logs --tail=50 traefik socket-proxy

Read service logs for the bounded number of recent lines requested by --tail. Expected: normal startup/request messages without persistent parser, permission or discovery errors. Startup discovery errors can clear on retry; persistent ones need a permissions/API check. An absolute -f path selects infrastructure independently of your current directory.

bash
sudo docker compose port socket-proxy 2375

Check whether the socket proxy’s API port is published on the host. Expected: no mapping; a nonzero exit is possible. Never publish 2375 to fix discovery problems.

8. Deploy the landing page and verify HTTPS

8.1 Create the landing page HTML

Prepare a simple page whose content makes successful deployment easy to recognize.

VPS, deploy: create the landing page in its own project directory.

bash
cd /srv/apps/landing

Change the current terminal’s working directory to /srv/apps/landing. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
mkdir -p html

Create html if it is missing. -p also creates missing parent directories and accepts an existing directory. Expected: no output on success; existing files are retained.

bash
nano html/index.html

Create the landing page with the complete HTML below. Save with Ctrl+O, Enter, then exit with Ctrl+X. Expected: html/index.html contains My VPS is online. This tutorial-owned directory can receive a container SELinux label.

xml
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>My VPS</title></head>
<body><h1>My VPS is online</h1><p>Landing page served by Nginx.</p></body>
</html>

8.2 Configure the landing container and hostname

Attach Nginx to proxy and associate your domain with its internal web port.

VPS, deploy, /srv/apps/landing: configure this independent static-site project.

bash
cp /srv/infra/traefik/.env .env

Copy /srv/infra/traefik/.env to this project’s .env. Expected: no output and a local .env containing the pinned image references. Compose does not automatically read another project’s .env; do not overwrite an existing customized file without inspecting it.

bash
nano compose.yaml

Create the landing Compose file using the complete YAML below. Replace example.com with your own domain, save with Ctrl+O, Enter, then exit with Ctrl+X. Expected: compose.yaml is saved here. The HTML mount is read-only and the app has no published host port.

yaml
name: landing
services:
  web:
    image: ${NGINX_IMAGE:?Set NGINX_IMAGE in .env}
    restart: unless-stopped
    volumes:
      - ./html:/usr/share/nginx/html:ro,Z
    networks:
      - proxy
    labels:
      traefik.enable: "true"
      traefik.docker.network: proxy
      traefik.http.routers.landing.rule: Host(`example.com`)
      traefik.http.routers.landing.entrypoints: websecure
      traefik.http.routers.landing.tls.certresolver: letsencrypt
      traefik.http.routers.landing.service: landing
      traefik.http.services.landing.loadbalancer.server.port: "80"
networks:
  proxy:
    external: true

The router matches the requested hostname, selects HTTPS and asks letsencrypt for its certificate. The service label tells Traefik to use internal Nginx port 80; traefik.docker.network avoids selecting the wrong network when an app has several. Labels configure Traefik, not DNS: the A record must already exist.

8.3 Validate and start the landing project

Check the Compose file, launch Nginx and inspect its state.

VPS, deploy, /srv/apps/landing: validate the stack and test both HTTP and HTTPS.

bash
sudo docker compose config -q

Validate this project’s Compose structure and variable substitution. -q suppresses normal output. Expected: no output and a successful exit. Stop on any error; this does not validate every application configuration file.

bash
sudo docker compose up -d

Create or update this Compose project’s containers and run them in the background (-d). Expected: creation/start messages without errors. The next status check confirms they remain running; startup alone does not prove the site works.

bash
sudo docker compose ps

List this project’s containers, states and port mappings. Expected: web Up and 80/tcp without a host port binding. Investigate exited, restarting or unhealthy states before proceeding.

8.4 Verify redirects, HTTPS, and page content

Check the complete public request path, including the first certificate issuance.

bash
curl -I http://example.com

Request HTTP response headers with -I. Expected: a redirect to your HTTPS URL, normally status 308. A timeout requires checking DNS, both firewalls and Traefik’s published port 80.

bash
curl -I https://example.com

Request HTTPS headers from https://example.com. Expected: status 200 with a trusted certificate. Certificate issuance can take a short time; inspect Traefik logs before retrying. Never use -k to claim TLS works. Also test from your PC to verify external reachability.

bash
curl -fsS https://example.com

Fetch the HTTPS page body: -f fails on HTTP errors, -s hides progress, and -S keeps error messages visible. Expected: My VPS is online in the response. Open the URL in a browser too: HTML retrieval does not verify JavaScript or the visible UI.

bash
sudo docker compose -f /srv/infra/traefik/compose.yaml logs --tail=100 traefik

Read service logs for the bounded number of recent lines requested by --tail. Expected: normal startup/request messages without persistent parser, permission or discovery errors. Startup discovery errors can clear on retry; persistent ones need a permissions/API check. An absolute -f path selects infrastructure independently of your current directory.

sequenceDiagram
    participant T as Traefik
    participant CA as Lets Encrypt
    participant FS as acme.json
    T->>CA: Request certificate for configured hostname
    CA->>T: HTTP-01 challenge over public port 80
    T-->>CA: Challenge response
    CA-->>T: Signed certificate
    T->>FS: Persist account and certificate keys
    Note over T,FS: Keep storage across container recreation
    T->>CA: Renew certificate before expiry

9. Create app1 and publish its source

9.1 Prepare Node.js, npm, and Git on your PC

Verify your local development tools and GitHub access before creating app1.

This path creates a working app instead of assuming you already own a repository. On your PC install a supported Node.js LTS release with npm and Git from their official sites. Create a GitHub account and configure GitHub SSH authentication on your PC. This PC key is separate from both the VPS login key and the read-only server deploy key created later.

PC: start in a parent folder for your projects. Stop after any error rather than pasting the whole procedure at once.

bash
node --version

PC, a parent folder for your projects: check Node.js is installed. Expected: a version number accepted by the current Vite requirements. Install a supported Node LTS release if missing or too old.

bash
npm --version

Check the npm package manager installed with Node.js. Expected: a version number. If the command is missing, fix the local Node/npm installation before creating app1.

bash
git --version

Check Git is installed on your PC. Expected: git version followed by a version number. Install it from the official site if the command is unavailable.

9.2 Create and build the Vue app

Generate a working local app and verify its production build.

bash
npm create vite@latest app1 -- --template vue

Generate a Vue project in a new app1 directory. -- passes the template option to create-vite. Approve installing create-vite if prompted. Expected: scaffolding completes with next-step instructions; resolve Node engine errors before continuing.

bash
cd app1

Change the current terminal’s working directory to app1. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
npm install

Install app1’s dependencies from package.json and create/update package-lock.json. Expected: installation completes and node_modules appears. Commit the lockfile so the production build can use npm ci.

bash
npm run build

Compile the Vue application for production using its build script. Expected: a successful build and generated dist directory. Fix build failures on the PC before publishing the source.

9.3 Create the Git repository and push the source

Save the initial source history and make it available to the VPS through GitHub.

bash
git init -b main

Initialize a local Git repository with main as the first branch. Expected: confirmation of repository initialization. This tracks source history; it does not upload anything yet.

bash
git add .

Stage the project files for the first commit, respecting .gitignore. Expected: no output. Check that secrets are excluded before committing.

bash
git commit -m "Create app1"

Record the staged files as a local Git commit; -m supplies its message. Expected: a commit summary. If identity is missing, set git config user.name and git config user.email in this repository with your own values, then retry.

bash
git remote add origin git@github.com:YOUR_GITHUB_USER/app1.git

First create an empty private app1 repository in GitHub without a README or license. Replace YOUR_GITHUB_USER, then register its SSH URL as origin. Expected: no output; this records an address but does not upload files.

bash
git push -u origin main

Upload main to GitHub using your PC’s GitHub SSH credentials. -u sets the upstream for later pushes. Expected: main appears in the private repository. Stop and fix authentication or repository errors before continuing.

9.4 Create the production Dockerfile

Build Vue in Node and copy only compiled files into the Nginx runtime image.

PC, app1 repository: use your editor to create Dockerfile, nginx.conf, .dockerignore and compose.yaml at the repository root with the following contents. Dockerfile builds static files in Node, then serves only dist in Nginx. The chosen Node 24 builder must satisfy your generated Vite version; keep the lockfile committed. Public Vite build variables are embedded in the browser bundle, so never put secrets in them.

dockerfile
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:stable-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=6 CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1

Dockerfile: WORKDIR sets the build directory; COPY first copies dependency manifests so Docker can cache npm ci, which installs exactly the lockfile versions. The later COPY includes source and RUN builds it. The second FROM starts a smaller runtime image without Node or source files. HEALTHCHECK probes local Nginx using Alpine wget. Pin both FROM images to reviewed digests using the pull/inspect method from step 7 before relying on reproducible builds.

9.5 Configure Nginx for Vue routes

Serve static assets and send client-side navigation requests to index.html.

plaintext
server {
    listen 80;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;
    location / {
        try_files $uri $uri/ /index.html;
    }
}

nginx.conf: listen uses internal port 80; root selects the compiled web files. try_files first serves a real file or directory, then falls back to index.html for Vue client-side routes. A static server does not execute backend code. This fallback also returns HTML for unknown paths; add explicit rules if your future app needs strict missing-asset responses.

9.6 Exclude unwanted files from the build

Keep dependencies, generated output and environment files out of the Docker build context.

plaintext
node_modules
dist
.git
.env
.env.*
!.env.example
*.log

.dockerignore excludes generated dependencies, build output, Git metadata, environment files and logs from the build context while retaining .env.example. It does not replace .gitignore: ensure real secret files are excluded from Git as well.

9.7 Define app1’s container and HTTPS route

Give app1 its own project identity and hostname without publishing a host port.

yaml
name: app1
services:
  web:
    build: .
    image: app1-web:current
    restart: unless-stopped
    networks:
      - proxy
    labels:
      traefik.enable: "true"
      traefik.docker.network: proxy
      traefik.http.routers.app1.rule: Host(`app1.example.com`)
      traefik.http.routers.app1.entrypoints: websecure
      traefik.http.routers.app1.tls.certresolver: letsencrypt
      traefik.http.routers.app1.service: app1
      traefik.http.services.app1.loadbalancer.server.port: "80"
networks:
  proxy:
    external: true

compose.yaml: replace app1.example.com with your real app hostname. build uses this repository’s Dockerfile and image names the local result app1-web:current. The unique router/service name app1 avoids collisions with landing. The network and TLS labels follow the already tested landing pattern. There is no host port and no VPS filesystem bind mount for app1.

9.8 Commit and push the deployment files

Make the production configuration available alongside the app source.

PC, app1 repository: commit and publish the production files after saving them.

bash
git add Dockerfile nginx.conf .dockerignore compose.yaml package-lock.json

PC, app1 repository: stage the deployment files and dependency lockfile. Expected: no output. Versioning these inputs lets a replacement VPS reproduce the deployment configuration.

bash
git commit -m "Add app1 production container"

Record the staged files as a local Git commit; -m supplies its message. Expected: a commit summary. If identity is missing, set git config user.name and git config user.email in this repository with your own values, then retry.

bash
git push

Upload the committed production configuration to GitHub. Expected: main is updated and the files are visible in the repository. Make future edits on the PC; the VPS deploy key will be read-only.

10. Connect GitHub and deploy app1

10.1 Create a dedicated GitHub deploy key

Allow the VPS to read app1’s private repository without granting push access.

VPS, deploy: prepare a separate, read-only GitHub identity for app1.

bash
mkdir -p ~/.ssh

Create ~/.ssh if it is missing. -p also creates missing parent directories and accepts an existing directory. Expected: no output on success; existing files are retained.

bash
chmod 700 ~/.ssh

Allow only deploy to access its SSH directory. Expected: no output. SSH may refuse authentication when private directories have unsafe permissions.

bash
ssh-keygen -t ed25519 -f ~/.ssh/github_app1 -C "app1-read-only-deploy"

Generate a dedicated Ed25519 GitHub key for app1 under deploy’s home. Choose a passphrase for manual deployments and never overwrite an existing key. Expected: private github_app1 and public github_app1.pub files plus a fingerprint.

bash
cat ~/.ssh/github_app1.pub

Display only the public key. Expected: one ssh-ed25519 line. In GitHub app1 → Settings → Deploy keys → Add deploy key, paste it and leave Allow write access unchecked. Keep the private file on the VPS.

10.2 Select the deploy key with an SSH alias

Ensure app1’s Git connections use the dedicated repository key.

bash
nano ~/.ssh/config

Save the GitHub alias shown below in deploy’s SSH configuration. Append it if other hosts already exist; do not replace them. Expected: the github-app1 alias selects the dedicated private key when Git connects.

plaintext
Host github-app1
    HostName github.com
    User git
    IdentityFile ~/.ssh/github_app1
    IdentitiesOnly yes

10.3 Protect the key and test GitHub access

Verify file permissions and authentication before cloning the repository.

VPS, deploy: verify GitHub authentication before cloning and deploying app1.

bash
chmod 600 ~/.ssh/config ~/.ssh/github_app1

Restrict the SSH configuration and private deploy key to deploy read/write access. Expected: no output. The public .pub file does not need to be copied anywhere else on the VPS.

bash
ssh -T git@github-app1

Test the GitHub alias without requesting a shell (-T). Verify GitHub’s host fingerprint using the official reference before accepting it. Expected: successfully authenticated, followed by a no-shell-access message; exit status 1 is normal for this test.

10.4 Clone app1 into its VPS directory

Retrieve the committed source and deployment configuration as deploy.

bash
git clone git@github-app1:YOUR_GITHUB_USER/app1.git /srv/apps/app1

Replace YOUR_GITHUB_USER and clone the repository using the read-only server key. Expected: source and deployment files appear in the empty /srv/apps/app1 directory. If it is not empty, inspect its contents instead of deleting files.

bash
cd /srv/apps/app1

Change the current terminal’s working directory to /srv/apps/app1. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

10.5 Build the image and start app1

Validate Compose, build the production image and wait for a healthy container.

bash
sudo docker compose config -q

Validate this project’s Compose structure and variable substitution. -q suppresses normal output. Expected: no output and a successful exit. Stop on any error; this does not validate every application configuration file.

bash
sudo docker compose build --pull

Build app1’s Dockerfile, checking for newer base-image references with --pull. Expected: a successful build tagged app1-web:current. Stop on failure; an old container may still run, but do not assume its current tag still identifies the old image.

bash
sudo docker compose up -d --wait --wait-timeout 120

Start/recreate app1 in the background and wait up to 120 seconds for healthy status. Expected: successful startup with a healthy web service. On timeout or failure, inspect logs and use the recovery procedure when appropriate.

bash
sudo docker compose ps

List this project’s containers, states and port mappings. Expected: web Up (healthy), with no host port binding. Investigate exited, restarting or unhealthy states before proceeding.

10.6 Verify app1 in HTTPS and in the browser

Check that the public hostname serves the app and that its JavaScript works.

bash
curl -I https://app1.example.com

Request HTTPS headers from https://app1.example.com. Expected: status 200 with a trusted certificate. Certificate issuance can take a short time; inspect Traefik logs before retrying. Never use -k to claim TLS works. Also test from your PC to verify external reachability.

flowchart LR
    PC[PC: edit and commit] -->|git push with PC key| GH[Private GitHub app1 repository]
    GH -->|git fetch using read-only deploy key| VPS[VPS: /srv/apps/app1]
    VPS -->|docker compose build| IMG[app1-web:current image]
    IMG -->|compose up and health check| N[Nginx container]
    T[Traefik] -->|HTTP on proxy| N
    U[Browser] -->|HTTPS app1.example.com| T

11. Add a second independent application

11.1 Create app2’s files and unique route

Reuse the static-site pattern with an independent project name and hostname.

VPS, deploy: create app2 using the already tested landing project as a pattern.

bash
cd /srv/apps/app2

Change the current terminal’s working directory to /srv/apps/app2. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
mkdir -p html

Create html if it is missing. -p also creates missing parent directories and accepts an existing directory. Expected: no output on success; existing files are retained.

bash
cp /srv/apps/landing/.env .env

Copy /srv/apps/landing/.env to this project’s .env. Expected: no output and a local .env containing the pinned image references. Compose does not automatically read another project’s .env; do not overwrite an existing customized file without inspecting it.

bash
nano html/index.html

Create app2’s HTML page using the complete example from step 8, changing its visible heading to App2 is online. Save and exit nano. Expected: a separate /srv/apps/app2/html/index.html; leave landing’s page unchanged.

bash
nano compose.yaml

Copy the complete landing Compose file into this new file. Change name: landing to name: app2, every router/service identifier landing to app2, and the Host domain to app2.example.com. Keep service web, the relative HTML mount and proxy network. Expected: a saved independent app2 configuration without changing landing or app1.

11.2 Validate and start app2

Launch the second project without changing landing or app1.

VPS, deploy, /srv/apps/app2: verify the new site and check that the existing sites still answer.

bash
sudo docker compose config -q

Validate this project’s Compose structure and variable substitution. -q suppresses normal output. Expected: no output and a successful exit. Stop on any error; this does not validate every application configuration file.

bash
sudo docker compose up -d

Create or update this Compose project’s containers and run them in the background (-d). Expected: creation/start messages without errors. The next status check confirms they remain running; startup alone does not prove the site works.

bash
sudo docker compose ps

List this project’s containers, states and port mappings. Expected: web Up and 80/tcp without a host port binding. Investigate exited, restarting or unhealthy states before proceeding.

11.3 Check all three public sites

Confirm app2 works and that existing hostnames still route correctly.

bash
curl -fsS https://app2.example.com

Fetch the HTTPS page body: -f fails on HTTP errors, -s hides progress, and -S keeps error messages visible. Expected: App2 is online in the response. Open the URL in a browser too: HTML retrieval does not verify JavaScript or the visible UI.

bash
curl -I https://app1.example.com

Request HTTPS headers from https://app1.example.com. Expected: status 200 with a trusted certificate. Certificate issuance can take a short time; inspect Traefik logs before retrying. Never use -k to claim TLS works. Also test from your PC to verify external reachability.

bash
curl -I https://example.com

Request HTTPS headers from https://example.com. Expected: status 200 with a trusted certificate. Certificate issuance can take a short time; inspect Traefik logs before retrying. Never use -k to claim TLS works. Also test from your PC to verify external reachability.

For further apps, repeat this pattern with a new directory, DNS record, image, hostname and unique project/router/service identifiers. Distinct Compose project names isolate lifecycle operations; distinct Traefik names avoid routing collisions.

flowchart TD
    D[New application] --> DNS[Create hostname A record]
    DNS --> DIR[Create dedicated project directory]
    DIR --> CFG[Unique Compose project and Traefik router names]
    CFG --> NET[Join proxy without publishing a host port]
    NET --> START[Validate, start, and request HTTPS]
    START --> TEST[Test new site and existing sites]

11.4 Plan private services for future apps

Keep future databases off the shared public-routing network and define data recovery first.

For a future database-backed app, attach only the web/API service to proxy and attach the database only to a separate internal network. Do not publish database ports. Store data in named volumes, keep secrets out of Git, and design database backups and migrations before deploying real data. This static-app tutorial does not supply a production database recovery procedure.

flowchart LR
    T[Traefik] -->|HTTP via proxy| W[Future web or API]
    subgraph Internal[Private backend network]
        W -->|Database protocol| DB[Database with named volume]
    end
    DB -->|Consistent database backup| BK[Encrypted off-site backup]
    Note[Database has no proxy membership and no published ports] -.-> DB

12. Update app1 and rehearse image recovery

12.1 Prepare the source change and check the checkout

Publish a tested source change, then confirm the server is on a clean main branch.

First change a visible heading on your PC, run npm run build, then git add, git commit and git push as before. The manual procedure below intentionally keeps recovery visible to a beginner. Run one deployment at a time. It assumes a clean main branch and a source-only static-app update; changes to Compose, secrets or persistent data require their own recovery plan.

VPS, deploy: update one deployment at a time and stop immediately at any failed check.

bash
cd /srv/apps/app1

Change the current terminal’s working directory to /srv/apps/app1. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
git status --short

Check for uncommitted changes before updating. Expected: no output. If files are listed, stop and resolve the changes; do not deploy over a dirty checkout.

bash
git branch --show-current

Check the checked-out branch. Expected: main. A different name or empty output is a stopping condition for this update procedure.

bash
git rev-parse HEAD

Print the exact current commit ID. Expected: a Git hash. Save it in your deployment notes before updating so you can identify the previously running source.

12.2 Preserve the working image

Keep a known-good local image before a build replaces the current tag.

bash
sudo docker image tag app1-web:current app1-web:rollback

Save another name for the current working image before rebuilding. Expected: no output. Do not replace this rollback tag again until the new deployment has been accepted, and do not prune this image.

12.3 Fetch the new source and build it

Advance main safely and build the candidate image without accepting a failed step.

bash
git fetch origin

Download remote commits without changing the checked-out files. Enter the server key’s passphrase if prompted. Expected: remote-branch updates or no output when nothing changed. Stop on authentication or network errors.

bash
git merge --ff-only origin/main

Advance local main only when it can fast-forward to origin/main. Expected: a fast-forward summary or Already up to date. If histories diverge, stop and resolve the situation on your PC instead of forcing a merge on the VPS.

bash
sudo docker compose config -q

Validate this project’s Compose structure and variable substitution. -q suppresses normal output. Expected: no output and a successful exit. Stop on any error; this does not validate every application configuration file.

bash
sudo docker compose build --pull

Build app1’s Dockerfile, checking for newer base-image references with --pull. Expected: a successful build tagged app1-web:current. Stop on failure; an old container may still run, but do not assume its current tag still identifies the old image.

12.4 Deploy and verify the update

Wait for health and inspect the changed page before accepting the deployment.

bash
sudo docker compose up -d --wait --wait-timeout 120

Start/recreate app1 in the background and wait up to 120 seconds for healthy status. Expected: successful startup with a healthy web service. On timeout or failure, inspect logs and use the recovery procedure when appropriate.

bash
curl -fsS https://app1.example.com

Fetch the HTTPS page body: -f fails on HTTP errors, -s hides progress, and -S keeps error messages visible. Expected: your expected app1 HTML in the response. Open the URL in a browser too: HTML retrieval does not verify JavaScript or the visible UI.

12.5 Recover the previous image if validation fails

Recreate the app from the saved image without rebuilding or pulling a replacement.

VPS, deploy: restore the saved image only after a deployment fails validation.

bash
cd /srv/apps/app1

Change the current terminal’s working directory to /srv/apps/app1. Expected: no output on success. Run the following commands in this same terminal; stop if the directory cannot be entered.

bash
sudo docker image inspect app1-web:rollback --format '{{.Id}}'

Confirm the saved recovery image exists and print its ID. Expected: sha256: followed by an image hash. If it is missing, stop: there is no local backup image for this procedure.

bash
sudo docker image tag app1-web:rollback app1-web:current

Point the current tag back to the saved working image. Expected: no output. This changes the image reference but does not yet replace the running container.

bash
sudo docker compose up -d --no-build --pull never --force-recreate --wait --wait-timeout 120

Recreate app1 from the restored local image. --no-build and --pull never prevent replacing it; --force-recreate ensures a new container uses it. --wait allows up to 120 seconds for health. Expected: successful startup; stop and inspect logs if health fails.

bash
sudo docker compose ps

List this project’s containers, states and port mappings. Expected: web Up (healthy), with no host port binding. Investigate exited, restarting or unhealthy states before proceeding.

bash
curl -I https://app1.example.com

Request HTTPS headers from https://app1.example.com. Expected: status 200 with a trusted certificate. Certificate issuance can take a short time; inspect Traefik logs before retrying. Never use -k to claim TLS works. Also test from your PC to verify external reachability.

After recovery, verify the old UI in a browser. Only the image is restored: Git and configuration files remain newer. Record the incident, then fix or revert source on your PC before the next normal deployment. Keep the rollback image on disk. Database rollback and zero-downtime deployment require different procedures.

flowchart TD
    A[Check clean main and save commit] --> B[Tag working image as rollback]
    B --> C[Fetch and fast-forward]
    C --> D[Validate configuration and build]
    D --> E[Recreate and wait for health]
    E --> Q{HTTPS and browser checks pass?}
    Q -->|Yes| OK[Accept deployment and record commit]
    Q -->|No| R[Retag rollback as current]
    R --> U[Force recreate without build or pull]
    U --> V[Verify restored site]
    V --> F[Fix source and review configuration before retry]

13. Diagnose problems without guessing

13.1 Inspect app1’s state, logs, and Nginx config

Determine whether the app container is running and serving valid web configuration.

VPS, deploy, any directory: these are separate diagnostic checks; run the one relevant to the symptom.

bash
sudo docker compose -f /srv/apps/app1/compose.yaml ps

List this project’s containers, states and port mappings. Expected: web Up (healthy), with no host port binding. Investigate exited, restarting or unhealthy states before proceeding.

bash
sudo docker compose -f /srv/apps/app1/compose.yaml logs --tail=100 web

Read the last 100 log lines from app1’s web container. The absolute -f path selects app1 from any directory. Expected: Nginx startup/access messages; inspect errors around failed requests. Redact request data before sharing logs.

bash
sudo docker compose -f /srv/apps/app1/compose.yaml exec web nginx -t

Run Nginx’s configuration test inside the running app1 web container using exec. The absolute -f path selects app1 from any directory. Expected: syntax is ok and test is successful. A stopped container cannot accept exec.

13.2 Check routing logs and host services

Look for proxy discovery failures and stopped Docker or firewall services.

bash
sudo docker compose -f /srv/infra/traefik/compose.yaml logs --since=10m traefik socket-proxy

Read service logs for the last ten minutes (--since=10m). Expected: normal startup/request messages without persistent parser, permission or discovery errors. Startup discovery errors can clear on retry; persistent ones need a permissions/API check. An absolute -f path selects infrastructure independently of your current directory.

bash
sudo systemctl is-active docker firewalld

Check both host services. Expected: active on two lines, one for Docker and one for firewalld. Investigate any inactive or failed result.

13.3 Check disk, memory, ports, and SELinux

Rule out host resource pressure and access problems before changing application code.

bash
df -h /srv

Show disk capacity for the filesystem containing /srv. -h uses readable units. Expected: space still available; investigate high usage before deleting files or building more images.

bash
free -h

Show RAM and swap usage with readable units. Expected: memory totals and an available column. Use available rather than free alone to judge whether the server has room for more work.

bash
sudo ss -tlnp

List listening (-l) TCP (-t) sockets with numeric addresses (-n) and process details (-p). Expected: SSH is visible. Docker NAT can publish ports without a listening process here, so also check Compose’s port mappings.

bash
getenforce

Check the host SELinux mode. Expected: Enforcing. If a bind mount is blocked, inspect its labels and audit logs rather than disabling host enforcement.

13.4 Follow the symptom to the failing layer

Use the decision tree to choose the next check instead of changing settings blindly.

flowchart TD
    FAIL[Site does not work] --> DNS{Hostname resolves to VPS?}
    DNS -->|No| D[Fix A and stale AAAA records]
    DNS -->|Yes| CON{Public 80 and 443 reachable?}
    CON -->|No| FW[Check provider firewall, firewalld and Traefik ports]
    CON -->|Yes| TLS{Certificate valid?}
    TLS -->|No| AC[Read ACME logs, check port 80 and DNS]
    TLS -->|Yes| STATUS{Response status?}
    STATUS -->|404| ROUTE[Check Host rule, labels and entrypoint]
    STATUS -->|502 or 504| NET[Check proxy network and internal app port]
    STATUS -->|200 but broken UI| UI[Browser console, assets and source build]
    NET --> HEALTH[Inspect app health and Nginx logs]

A Traefik 404 often means no matching router; 502/504 usually means the router exists but the backend is unreachable. A certificate error needs DNS, port 80 and ACME log checks; repeatedly deleting acme.json can trigger issuance limits and loses account state. On disk-full errors, inspect usage before removing anything; prune commands can delete recovery images and volumes. Redact credentials and request data before sharing logs.

14. Back up, restore, and maintain the server

14.1 Create and inspect a local backup archive

Capture private configuration and static pages in restricted staging storage.

VPS, deploy: create and inspect a private local configuration archive before exporting it.

bash
sudo install -d -m 700 /var/backups/vps

Create a root-only local backup directory. -m 700 reserves traversal, reads and writes to root. Expected: no output; this is private staging storage on the VPS, not an off-site backup.

bash
sudo tar -czf /var/backups/vps/config-$(date -u +%Y%m%dT%H%M%SZ).tar.gz -C /srv infra apps/landing apps/app2

Create (-c) a gzip-compressed (-z) archive named by -f, with a UTC date in its filename. -C /srv makes stored paths relative to /srv. Expected: no output on success. The archive includes infrastructure, ACME keys and both static sites; protect it as private material.

bash
sudo ls -lh /var/backups/vps

List backup filenames and readable sizes (-lh). Expected: a nonempty timestamped archive. Copy its exact filename for the next command; ARCHIVE_NAME is a placeholder, not a literal filename.

bash
sudo tar -tzf /var/backups/vps/ARCHIVE_NAME.tar.gz

Replace ARCHIVE_NAME with the saved archive’s actual name. List (-t) its compressed contents without extracting. Expected: infra, apps/landing and apps/app2 paths. Successful listing does not prove restoration works; rehearse restoration separately.

Encrypt the archive and keep a copy off the VPS. app1’s committed source, configuration and lockfile remain in GitHub; separately preserve any uncommitted settings, secrets and reviewed image digests.

14.2 Prepare an archive for secure transfer

Give deploy access to one selected archive without opening the root-only backup directory.

To copy the root-owned archive safely, first replace ARCHIVE_NAME in the following VPS commands. They create a private directory for deploy, copy one selected archive there, and grant only deploy read/write access. The unencrypted staging copy is sensitive; retain it only as required by your backup policy.

VPS, deploy: prepare one selected archive for the PC transfer below.

bash
install -d -m 700 /home/deploy/backup-export

As deploy, create a private export directory in your home. Expected: no output. Only deploy can enter it to retrieve the selected archive over SSH.

bash
sudo install -o deploy -g deploy -m 600 /var/backups/vps/ARCHIVE_NAME.tar.gz /home/deploy/backup-export/ARCHIVE_NAME.tar.gz

Replace ARCHIVE_NAME in both paths. Copy that one root-owned archive to the export directory, with deploy ownership and mode 600. Expected: no output; deploy can read the export copy. Keep this unencrypted staging copy only as required by your retention policy.

14.3 Copy to your PC and keep an encrypted off-site backup

Move the backup away from the VPS and protect its private keys and settings.

bash
scp -i ./vps_deploy deploy@VPS_IP:/home/deploy/backup-export/ARCHIVE_NAME.tar.gz .

PC, the folder containing vps_deploy: scp transfers the selected archive through SSH into the current PC directory (the final dot). Expected: a completed transfer and a nonempty local file. Encrypt this copy with your chosen backup tool and store it in a separate account/location; verify that you can decrypt and list it. Schedule backups, define retention, and alert on failures before hosting important data. Never commit archives, SSH private keys or acme.json to Git.

flowchart LR
    CFG[Configuration and ACME state] --> LOCAL[Restricted local archive]
    LOCAL -->|SSH transfer| PC[Private PC staging]
    PC -->|Encrypt and upload| OFF[Independent off-site storage]
    GH[app1 Git repository and pinned build inputs] --> RESTORE[Replacement VPS rehearsal]
    OFF -->|Decrypt and restore privately| RESTORE
    RESTORE --> TEST[Check permissions, labels, health and HTTPS]

14.4 Rehearse restoration on a disposable VPS

Prove the backup can recreate working sites before relying on it for recovery.

Rehearse on a disposable VPS: provision the same OS, recreate deploy and Docker, transfer/decrypt the archive into a private temporary directory, inspect it, then restore only reviewed paths under /srv. Recreate proxy, restore file ownership and SELinux labels, keep acme.json mode 600, and clone app1 again with a newly authorized deploy key. Validate Compose before starting infrastructure and apps. Coordinate DNS cutover so only the intended VPS answers certificate challenges. Successful listing alone is not a restore test; verify actual pages and certificates. Databases later need application-consistent dumps and their own restore rehearsal, not a live-volume tar.

14.5 Plan updates and monitoring

Keep software current and detect disk, certificate, availability and backup failures.

For routine maintenance, check disk/memory and logs, install OS security updates in a planned window, and reboot when required. For container upgrades, pull reviewed tags, record new digests, update only the relevant .env or Dockerfile, recreate that stack and repeat HTTPS/browser checks. Restarting a container alone does not update its image. Monitor each public URL externally, certificate expiry, disk capacity and backup freshness. This VPS remains a single point of failure.

15. Completion checklist and official references

15.1 Verify the completion criteria

Use observable checks to confirm the setup is ready for your intended use.

You are finished when key-only deploy SSH and sudo work; root/password SSH is disabled; Docker and firewalld start at boot; only intended ports are public; the socket proxy has no published port; all three domains serve the right site with trusted HTTPS; app1 is healthy and its browser UI works; you have rehearsed image recovery; and an encrypted off-site backup has passed a restore rehearsal. Do not mark a step complete solely because the command exited successfully.

15.2 Consult the official references

Use these upstream documents for version requirements, fingerprints and detailed configuration options.

Docker Engine installation on AlmaLinux

Docker networking and firewalls

Traefik Docker provider reference

Traefik ACME certificate reference

Docker socket proxy permissions and limitations

GitHub SSH host fingerprints

Connect your PC to GitHub over SSH

Install Node.js LTS

Install Git

Vite setup and Node version requirements

Diagram
100%