eco Beginner Tutorial/How-to

Installing Invoice Ninja on a VPS: Docker, SSL, SMTP, Cron, and Backups

We earn commissions when you shop through the links below.

calendar_month Oct 29, 2026 schedule 19 min read visibility 695 views
Установка Invoice Ninja на VPS: Docker, SSL, SMTP, cron и бэкапы
dns No server for this guide yet? Vultr, DigitalOcean, Contabo sellDeal WebHosting UK: 10% off managed VPS until Nov 30 Get deal →

Installing Invoice Ninja on a VPS: Docker, SSL, SMTP, cron, and backups

TL;DR

Invoice Ninja can be deployed on a VPS using Docker Compose: the application, MySQL, and Redis run in isolation, Caddy automatically obtains a TLS certificate, and cron performs database and file backups. Below is a practical setup for Ubuntu Server 24.04 LTS.

  • We use Invoice Ninja 5.x, Docker Engine, and Docker Compose v2.
  • We place the application behind Caddy with automatic HTTPS.
  • We configure SMTP for sending invoices and notifications.
  • We create a system user, SSH access, UFW, and Fail2ban.
  • We configure daily MySQL dumps and backups using Restic to S3-compatible storage.
  • We check the containers, HTTPS, SMTP, the task queue, and backup restoration.

1. TL;DR

This guide covers installing Invoice Ninja on your own VPS without manually installing PHP, Composer, and a web server. Docker runs Invoice Ninja, MySQL, and Redis, Caddy handles HTTPS requests and automatically renews the certificate, while cron runs backups.

  • Operating system: Ubuntu Server 24.04 LTS.
  • Domain: for example, billing.example.com.
  • Minimum working server: 2 vCPU, 4 GB RAM, and 40 GB SSD.
  • For a small company, 4 vCPU, 8 GB RAM, and 80 GB NVMe are preferable.
  • Ports 80 and 443 are used by Caddy, and port 22 is used for SSH.

dnsA server for this guide

Matching plans from verified providers, prices updated daily.

sell WebHosting UK: 10% off managed VPS · until Nov 30 Get deal →

Compare:Vultr vs DigitalOceanVultr vs ContaboAll VPS by price

Affiliate links: we may earn a commission, your price stays the same.

2. Contents

The material is structured as a sequential scenario: from selecting resources and basic server protection to checking email, restoring the database, and performing regular maintenance.

  1. Defining requirements and architecture.
  2. Preparing the VPS and SSH access.
  3. Installing Docker Engine and Compose.
  4. Creating the Docker Compose configuration.
  5. Configuring the domain, Caddy, and TLS.
  6. Connecting SMTP and background tasks.
  7. Configuring backups.
  8. Troubleshooting errors and answering frequently asked questions.

3. What we are configuring and why

What is Invoice Ninja

Invoice Ninja is a web application for issuing invoices, quotes, recurring invoices, managing clients, and accepting payments. The self-hosted version is suitable for freelancers, small agencies, and companies that need control over their data, domain, and document delivery process.

With a self-managed installation, the application runs on your server. Client data and invoices are stored in your database, while emails are sent through the selected SMTP provider. This differs from the SaaS scenario, where infrastructure, updates, and backups are controlled by an external platform.

Final architecture

After completing the instructions, the setup will look as follows:

Component Purpose Public access
Caddy HTTPS, automatic certificates, and reverse proxy 80, 443
Invoice Ninja Web interface and API Only through Caddy
MySQL 8 Storage for clients, invoices, and settings Internal Docker network only
Redis 7 Cache and background task queues Internal Docker network only
Restic Encrypted backups Outgoing connections to S3

What will work after installation

  • Logging in to Invoice Ninja at an address such as https://billing.example.com.
  • Creating clients, products, invoices, and templates.
  • Sending invoices by email through SMTP.
  • Generating PDF files and storing user uploads.
  • Background tasks through Redis and a worker container.
  • Daily encrypted backups of the database and files.

Cloud-managed or self-hosted

The cloud option is easier to start using: there is no need to update the server, monitor disk space, or verify backup restoration. In return, you pay a recurring subscription and accept limitations regarding data, integrations, and settings.

Self-hosted Invoice Ninja on a VPS requires more responsibility. You need to update images, restrict access, monitor SMTP, and verify backups yourself. However, fixed server rental costs are usually predictable, and data can be stored in the jurisdiction of your choice.

A VPS is a practical compromise for a single project or a small team. A dedicated server is justified with a large number of clients, a high volume of PDFs, several business applications running in parallel, or strict resource isolation.

What is not covered in this scenario

This guide does not configure a payment gateway, accounting integration, DNS server, or corporate SMTP. These parameters depend on the country, bank, and selected provider. Payments will additionally require API keys and verification of webhook addresses.

4. What VPS configuration is needed for this task

Invoice Ninja does not require a powerful server for several users, but sufficient RAM is important for MySQL, Redis, Docker, and PDF generation. Do not rely solely on average CPU usage: short-term peaks occur during mass invoice delivery and document generation.

Minimum requirements

Resource Minimum Practical option
CPU 2 vCPU 4 vCPU
RAM 4 GB 8 GB
Disk 40 GB SSD 80–120 GB NVMe
Network 100 Mbps 1 Gbps or good burst
IPv4 1 public address 1 IPv4 and IPv6 if needed
OS Ubuntu 24.04 LTS Ubuntu 24.04 LTS

The minimum configuration is suitable for one owner, several employees, and a small number of invoices per month. If CRM, GitLab, Mattermost, or monitoring also run on the server, 4 GB of RAM will quickly become a limitation.

For a typical small company, you can choose a suitable VPS with 4 vCPU, 8 GB of RAM, an NVMe disk of at least 80 GB, and backups or separate S3 storage.

When a dedicated server is needed

A dedicated server makes sense if Invoice Ninja serves tens of thousands of clients, generates a large number of PDFs simultaneously, or runs alongside other resource-intensive services. It is also useful when dedicated cores, local NVMe drives, and complete isolation from other tenants are required.

For a single Invoice Ninja installation, a dedicated server is usually excessive. The additional costs do not eliminate the need for backups, updates, and security configuration. Before switching, it is better to measure CPU, RAM, and I/O usage, as well as queue execution time.

Server location

Location affects interface latency, PDF download speed, and personal data storage requirements. The server should preferably be located closer to the employees and clients who work with the system most often. If users are located in different regions, choose a data center with good international peering.

For email, geography is less important than IP address reputation. Make sure that the provider allows outgoing SMTP and that the PTR record can be configured correctly. For sending email, it is generally safer to use an external SMTP service rather than your own mail server.

5. Server preparation

The instructions below assume a clean Ubuntu Server 24.04 LTS installation with access as a user having root privileges. All commands are executed in an SSH session. Replace the values in angle brackets with your own data.

Creating an administrative user

# Создаём отдельного пользователя для администрирования
sudo adduser deploy

# Добавляем пользователя в группу sudo
sudo usermod -aG sudo deploy

# Проверяем членство в группе
id deploy

Do not use root for everyday work. The deploy user will run commands through sudo, while Docker commands can be executed under this user after adding it to the Docker group.

Configuring an SSH key

On the local computer, create an Ed25519 key if you do not already have one:

# Выполняется на локальном компьютере
ssh-keygen -t ed25519 -C "deploy-invoiceninja"

# Копируем открытый ключ на сервер
ssh-copy-id deploy@SERVER_IP

Open a separate SSH session under the new user and make sure that login works. Only after verification should you disable password login.

# Открываем конфигурацию SSH
sudo nano /etc/ssh/sshd_config.d/ hardening.conf

There should be no space between the directory name and the file in the command above. Use the correct command:

# Создаём файл дополнительных настроек SSH
sudo nano /etc/ssh/sshd_config.d/hardening.conf

Add the following settings:

PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
# Проверяем синтаксис конфигурации SSH
sudo sshd -t

# Перезапускаем SSH без закрытия текущей сессии
sudo systemctl reload ssh

Updating Ubuntu and basic utilities

# Обновляем индекс пакетов и устанавливаем последние исправления
sudo apt update && sudo apt full-upgrade -y

# Устанавливаем утилиты для администрирования, TLS и резервного копирования
sudo apt install -y ca-certificates curl gnupg lsb-release \
    git unzip jq nano vim htop ncdu ufw fail2ban restic apache2-utils

# Перезагружаем сервер, если обновлялось ядро
sudo reboot

After rebooting, connect again as deploy. Do not install multiple web servers simultaneously. In this guide, HTTP and HTTPS are served by Caddy in a container.

Configuring UFW

# Разрешаем SSH, HTTP и HTTPS
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Включаем межсетевой экран
sudo ufw --force enable

# Проверяем активные правила
sudo ufw status verbose

Do not expose MySQL, Redis, or the application's internal port to the outside. The Docker network provides communication between containers, and only Caddy should remain public.

Configuring Fail2ban

# Создаём локальную конфигурацию Fail2ban
sudo nano /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
port = 22
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1h
# Запускаем Fail2ban и добавляем его в автозагрузку
sudo systemctl enable --now fail2ban

# Проверяем состояние SSH-защиты
sudo fail2ban-client status sshd

Fail2ban does not replace SSH keys or a firewall. It only temporarily blocks addresses that repeatedly violate login rules.

6. Software Installation — Step by Step

Step 1. Installing Docker Engine

Use the official Docker repository rather than old packages from the standard Ubuntu repository. As of 2026, Docker Engine 28.x or a newer compatible version and Docker Compose v2 are suitable for this setup.

# Create a directory for Docker repository keys
sudo install -m 0755 -d /etc/apt/keyrings

# Download the official repository key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
    sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg

# Allow the package manager to read the key
sudo chmod a+r /etc/apt/keyrings/docker.gpg

# Add the official Docker repository for Ubuntu 24.04
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu noble stable" | \
    sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Update the package index
sudo apt update

# Install Docker Engine, CLI, and Compose plugin
sudo apt install -y docker-ce docker-ce-cli containerd.io \
    docker-buildx-plugin docker-compose-plugin

# Start Docker at system startup
sudo systemctl enable --now docker

# Allow the deploy user to work with Docker
sudo usermod -aG docker deploy

Log out of SSH and log in again so that the user's group is updated:

# Check Docker and Compose versions
docker version
docker compose version

# Check Docker using a test container
docker run --rm hello-world

Step 2. Creating the Application Directory

# Create a separate project directory
sudo mkdir -p /opt/invoiceninja/{caddy,data/mysql,data/redis,backups,config}

# Assign the directory to the deploy user
sudo chown -R deploy:deploy /opt/invoiceninja

# Change to the working directory
cd /opt/invoiceninja

Step 3. Creating the Secrets File

The .env file contains database passwords and the application key. It must not be committed to Git, placed in a publicly accessible web directory, or included in an unencrypted public backup.

# Generate random values
APP_KEY_VALUE="base64:$(openssl rand -base64 32 | tr -d '\n')"
MYSQL_ROOT_VALUE="$(openssl rand -hex 24)"
MYSQL_PASSWORD_VALUE="$(openssl rand -hex 24)"
RESTIC_PASSWORD_VALUE="$(openssl rand -base64 32 | tr -d '\n')"

# Create the environment file
cat > /opt/invoiceninja/.env <<EOF
TZ=UTC
APP_URL=https://billing.example.com
APP_KEY=${APP_KEY_VALUE}
APP_DEBUG=false
REQUIRE_HTTPS=true

MYSQL_DATABASE=ninja
MYSQL_USER=ninja
MYSQL_PASSWORD=${MYSQL_PASSWORD_VALUE}
MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_VALUE}

DB_HOST=db
DB_PORT=3306
DB_DATABASE=ninja
DB_USERNAME=ninja
DB_PASSWORD=${MYSQL_PASSWORD_VALUE}

REDIS_HOST=redis
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=smtp.example.net
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=CHANGE_ME_SMTP_PASSWORD
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME=Billing

RESTIC_REPOSITORY=s3:s3.example.net/invoiceninja
RESTIC_PASSWORD=${RESTIC_PASSWORD_VALUE}
AWS_ACCESS_KEY_ID=CHANGE_ME_S3_KEY
AWS_SECRET_ACCESS_KEY=CHANGE_ME_S3_SECRET
EOF

# Restrict access to the secrets
chmod 600 /opt/invoiceninja/.env

Replace billing.example.com, the SMTP parameters, and the S3 keys. Do not use the Invoice Ninja panel password as the database or SMTP password.

Step 4. Creating Docker Compose

Create the compose.yml file. The Invoice Ninja 5.x image contains the Laravel application. It is better to pin the image version to a specific stable tag after checking the release notes rather than blindly using latest.

services:
  app:
    image: invoiceninja/invoiceninja:5
    restart: unless-stopped
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    expose:
      - "80"
    volumes:
      - app_storage:/var/www/app/storage
      - app_public_storage:/var/www/app/public/storage
    networks:
      - internal

  worker:
    image: invoiceninja/invoiceninja:5
    restart: unless-stopped
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    command: ["php", "artisan", "queue:work", "--sleep=3", "--tries=3", "--timeout=120"]
    volumes:
      - app_storage:/var/www/app/storage
      - app_public_storage:/var/www/app/public/storage
    networks:
      - internal

  scheduler:
    image: invoiceninja/invoiceninja:5
    restart: unless-stopped
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    command: ["sh", "-c", "while true; do php artisan schedule:run; sleep 60; done"]
    volumes:
      - app_storage:/var/www/app/storage
      - app_public_storage:/var/www/app/public/storage
    networks:
      - internal

  db:
    image: mysql:8.0
    restart: unless-stopped
    command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    environment:
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      TZ: ${TZ}
    volumes:
      - ./data/mysql:/var/lib/mysql
    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h localhost -uroot -p$${MYSQL_ROOT_PASSWORD}"]
      interval: 10s
      timeout: 5s
      retries: 20
    networks:
      - internal

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - ./data/redis:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 10
    networks:
      - internal

  caddy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./config/Caddyfile:/etc/caddy/Caddyfile:ro
      - ./caddy/data:/data
      - ./caddy/config:/config
    depends_on:
      - app
    networks:
      - internal

volumes:
  app_storage:
  app_public_storage:

networks:
  internal:
    driver: bridge

Image tags should be pinned after successful testing. Save the current tag and make a backup before updating. Do not remove Docker volumes with the docker compose down -v command unless you want to destroy the data.

Step 5. Starting the Database and Application

# Check Compose syntax and variable substitution
docker compose config

# Pull images and create containers
docker compose pull

# Start MySQL, Redis, Invoice Ninja, worker, and scheduler
docker compose up -d

# View the status of all services
docker compose ps

The first startup may take several minutes. MySQL initially creates system tables, after which Docker Compose marks the service as healthy.

Step 6. Checking Migrations and Logs

# View the application's latest messages
docker compose logs --tail=100 app

# Check the status of the database and Redis
docker compose ps db redis

# Run migrations manually if necessary
docker compose exec app php artisan migrate --force

# Clear the configuration cache after changing .env
docker compose exec app php artisan optimize:clear

If the application reports that the encryption key is missing, check that a valid APP_KEY is set in .env. Do not generate a new key on an installation that is already running: previously encrypted data may become inaccessible.

7. Configuration

DNS and Domain Name

Before starting Caddy, create an A record for the domain pointing to the VPS IPv4 address. If IPv6 is used, add an AAAA record only after verifying that the server is actually accessible over IPv6 and that the firewall is configured for this protocol.

# Check where the domain points
dig +short billing.example.com A
dig +short billing.example.com AAAA

The expected result for the A record is the public VPS address. If DNS has not been updated yet, Caddy will be unable to complete the HTTP-01 challenge and obtain a certificate.

Caddy Configuration

# Create the reverse proxy configuration
cat > /opt/invoiceninja/config/Caddyfile <<'EOF'
billing.example.com {
    encode gzip zstd

    reverse_proxy app:80

    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "SAMEORIGIN"
        Referrer-Policy "strict-origin-when-cross-origin"
    }

    log {
        output file /data/access.log
        format json
    }
}
EOF

# Restart Caddy with the new domain
docker compose up -d caddy

# View certificate issuance
docker compose logs -f caddy

Caddy automatically creates a certificate through ACME and stores it in the /opt/invoiceninja/caddy/data directory. Always include this directory in backups, or be prepared to obtain the certificate again during restoration.

HTTPS Check

# Check HTTP headers and the TLS response
curl -I https://billing.example.com

# Check the redirect or HTTP availability
curl -I http://billing.example.com

# Check that the application responds through the local Docker DNS
docker compose exec caddy wget -qO- http://app/ | head

The curl command should receive a response from Caddy without a certificate error. A 200, 302, or login page is acceptable. A 502 error means that Caddy is working but cannot connect to the application container.

SMTP

To send email, use an SMTP provider with port 587 and STARTTLS, or port 465 with TLS if explicitly supported by your service. In most cases, port 587 with MAIL_ENCRYPTION=tls is the most compatible option.

# Open the environment variables
nano /opt/invoiceninja/.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.example.net
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=длинный-пароль-или-app-password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME=Billing
# Recreate the containers so they receive the new variables
docker compose up -d --force-recreate app worker scheduler

# Clear the application's configuration cache
docker compose exec app php artisan optimize:clear

# Check application logs after a test email
docker compose logs --tail=100 app worker

If the SMTP provider requires a separate app password, use that password specifically. The regular mailbox password may be prohibited by the security policy. Also check the sender domain's SPF, DKIM, and DMARC records; otherwise, messages may end up in spam.

Background Tasks and cron

Two separate services are running in Compose. worker processes the queue, while scheduler runs the Laravel scheduler every minute. This is preferable to a single cron process inside the container: the processes have separate logs and are automatically restarted by Docker.

# Check that worker and scheduler are running
docker compose ps worker scheduler

# View queue processing
docker compose logs --tail=100 worker

# Check Redis
docker compose exec redis redis-cli ping

The PONG response confirms that Redis is available. If the worker keeps restarting, first check the MySQL connection, the APP_KEY value, and the container logs.

Checking Docker Status

# Show containers and their health status
docker compose ps

# Check disk usage
df -h

# Check resource consumption by containers
docker stats --no-stream

# Check open TCP ports on the server
sudo ss -tulpn

The list of public ports should include SSH, HTTP, and HTTPS. MySQL and Redis should not listen on the host address. If you see 0.0.0.0:3306 or 0.0.0.0:6379, check the Compose file and remove the publication of these ports.

8. Backups and maintenance

What needs to be backed up

To fully restore Invoice Ninja, you need to save more than just the database. The database contains clients, invoices, and settings, but uploaded logos, attachments, and generated files are stored in Docker volumes.

  • MySQL dump.
  • app_storage volume.
  • app_public_storage volume.
  • .env file.
  • compose.yml file.
  • Caddyfile file.
  • Caddy directory with ACME data.

A backup on the same VPS is not full protection. If the server is deleted, the disk fails, or root is compromised, an attacker may also delete local copies. Use external S3-compatible storage, a separate VPS, or object storage with versioning and lifecycle policies.

Installing and configuring Restic

Restic encrypts data before sending it to remote storage. The repository password must not be lost: without it, restoring files is impossible. Store it separately from the server, for example in a secrets manager.

# Initialize a Restic repository in S3
cd /opt/invoiceninja
set -a
. ./.env
set +a
restic init

The command will request a password if the RESTIC_PASSWORD variable was not passed to the environment. Make sure the S3 path is correct for your provider.

Backup script

# Create a temporary files directory
mkdir -p /opt/invoiceninja/backups/tmp

# Create the backup script
cat > /opt/invoiceninja/backup.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail

PROJECT="/opt/invoiceninja"
TMP="${PROJECT}/backups/tmp"
STAMP="$(date -u +%Y-%m-%d_%H-%M-%S)"

cd "$PROJECT"
set -a
. "$PROJECT/.env"
set +a

mkdir -p "$TMP/$STAMP"

echo "[$(date -Is)] Creating MySQL dump"
docker compose exec -T db sh -c \
  'exec mysqldump --single-transaction --quick --routines --triggers \
  -uroot -p"$MYSQL_ROOT_PASSWORD" "$MYSQL_DATABASE"' \
  > "$TMP/$STAMP/mysql.sql"

echo "[$(date -Is)] Archiving application files"
tar -czf "$TMP/$STAMP/application.tar.gz" \
  .env compose.yml config/Caddyfile \
  caddy/data caddy/config \
  "$(docker volume inspect --format '{{.Mountpoint}}' invoiceninja_app_storage)" \
  "$(docker volume inspect --format '{{.Mountpoint}}' invoiceninja_app_public_storage)"

echo "[$(date -Is)] Uploading encrypted snapshot"
restic backup "$TMP/$STAMP" --tag invoiceninja

echo "[$(date -Is)] Removing temporary files"
rm -rf "$TMP/$STAMP"

echo "[$(date -Is)] Applying retention policy"
restic forget --tag invoiceninja \
  --keep-daily 7 \
  --keep-weekly 4 \
  --keep-monthly 6 \
  --prune

echo "[$(date -Is)] Backup completed"
EOF

# Make the script executable
chmod 700 /opt/invoiceninja/backup.sh

Docker volume names depend on the Compose project name. If the project directory was renamed, the docker volume inspect command may return a different name. Check it in advance:

# Show the actual volume names
docker volume ls | grep invoiceninja

If the name differs, replace it in the script. Run the backup manually before using it in cron.

# Perform the first full backup
sudo -u deploy /opt/invoiceninja/backup.sh

# Check the list of snapshots in the remote repository
cd /opt/invoiceninja
set -a
. ./.env
set +a
restic snapshots

Running via cron

# Open the deploy user's cron
crontab -e
# Daily backup at 03:15 UTC
15 3    /opt/invoiceninja/backup.sh >> /opt/invoiceninja/backups/backup.log 2>&1

Choose the time based on the time zone and workload. For critical billing, you can create additional copies before an update. The cron log should also be size-limited or cleared periodically.

Recovery testing

A backup that has never been restored cannot be considered verified. The minimum test is to download the latest snapshot to a separate test machine and make sure the SQL dump opens and user files are present.

# View the contents of the latest snapshot
restic snapshots

# Restore the latest snapshot to a temporary directory
mkdir -p /tmp/invoiceninja-restore
restic restore latest --target /tmp/invoiceninja-restore

# Check the SQL file
ls -lh /tmp/invoiceninja-restore
head -n 20 /tmp/invoiceninja-restore//mysql.sql

Perform a full recovery on a new server: install Docker, restore .env, deploy the Compose file, import the database, and copy the data into the volumes. Do not experiment with restoring the only working installation.

Updates

Create a snapshot and record the current image versions before updating:

# Save the configuration before updating
cd /opt/invoiceninja
docker compose config > compose-resolved-before-update.yml
./backup.sh

# Pull new images
docker compose pull

# Recreate containers without deleting volumes
docker compose up -d

# Check the logs after the update
docker compose logs --tail=200 app worker scheduler

A short maintenance window is sufficient for a small project. Before a major update, test the new tag on a separate copy first. Do not update Ubuntu, Docker, MySQL, and Invoice Ninja simultaneously unless necessary: if something goes wrong, it will be harder to identify the cause.

Rolling updates of multiple application instances are possible, but usually unnecessary for a small VPS. With a single instance, it is safer to schedule a few minutes of downtime and check migrations, login, PDF creation, and email delivery.

Monthly checks

  • Check free space with the df -h command.
  • Remove old Docker images after verifying the update.
  • Check whether cron completed successfully and the date of the latest Restic snapshot.
  • Check the TLS certificate expiration date.
  • Test email delivery and PDF generation.
  • Review Caddy, application, and worker logs.
  • Update Ubuntu and Docker during the scheduled maintenance window.
# Remove unused images, but not volumes
docker image prune -f

# Check the status of OS services
systemctl --failed

# Check the date of the latest backup
restic snapshots --tag invoiceninja

9. Troubleshooting and FAQ

Why does Caddy return 502 Bad Gateway?

First check docker compose ps and the logs with docker compose logs app caddy. A 502 code usually means that the application container is not running, is still performing migrations, or Caddy is using the wrong service name. The Caddyfile must contain the address app:80, and both containers must be on the same Docker network. Also check that the application did not exit because of an incorrect APP_KEY or database parameters.

The HTTPS certificate is not issued. What should I check?

Make sure the DNS A record points to this VPS and that ports 80 and 443 are allowed in UFW and the provider's external firewall. Caddy must receive incoming requests directly, without a restricted CDN mode or incorrect NAT. Check the docker compose logs caddy logs. If the domain has not yet been delegated or still has an old AAAA record, the ACME check may be reaching another server.

What is the minimum suitable VPS configuration?

For one small installation, 2 vCPUs, 4 GB of RAM, and a 40 GB SSD are sufficient. This option is suitable for several users and a moderate number of invoices, but leaves little capacity for other services. A more practical minimum is 4 vCPUs, 8 GB of RAM, and an 80 GB NVMe drive. Choose the disk size based on PDFs, attachments, logs, and local temporary space, even if the main backups are stored in S3.

Which should I choose for this task — a VPS or dedicated server?

For one Invoice Ninja installation or a small company, choose a VPS: it is cheaper, easier to scale, and usually has sufficient resources. A dedicated server is justified with consistently high loads, a large number of parallel PDF tasks, multiple applications on one server, or dedicated hardware requirements. Before switching, measure RAM, CPU, and disk I/O. If the only bottleneck is the disk, a VPS with faster NVMe may sometimes be sufficient.

Emails are not being sent even though the SMTP data is correct

Check the port, encryption type, and SMTP provider requirements. Port 587 usually uses MAIL_ENCRYPTION=tls, while port 465 may require different settings. After changing .env, recreate the containers and run php artisan optimize:clear. Check the worker logs: the email may be in the queue but not being processed. Also verify that the sender address is permitted by the provider and has valid SPF/DKIM records.

The worker keeps restarting

Run docker compose logs --tail=200 worker. Common causes include an inaccessible database, an incorrect MySQL password, a missing APP_KEY, or incorrect Redis settings. Check docker compose exec redis redis-cli ping and the database status with docker compose ps db. After correcting the environment, run docker compose up -d --force-recreate worker. Do not delete volumes in an attempt to fix a regular configuration error.

Disk space is running out

First find large directories with df -h, du -xh /opt/invoiceninja | sort -h | tail, and docker system df. Check Caddy and Docker logs, the local temporary backup directory, and the size of user attachments. Do not manually delete MySQL files. Old images can be removed with docker image prune, and Restic retention can be configured with the forget policy. If data continues to grow, increase the disk size in advance.

How can I restore access after a configuration error?

If the containers start, restore the last working .env and Compose file from the encrypted backup, then run docker compose config and restart the services. If the problem appeared after an image update, revert to the previous verified tag. Do not generate a new APP_KEY or delete the database: this may make encrypted data and user records inaccessible.

Do I need to run a separate system cron for Invoice Ninja?

In this setup, a separate cron for the application is not needed: the scheduler container runs php artisan schedule:run every minute, while the worker processes the queue. The system cron is used only for backups. If the scheduler has stopped, check its status and logs. For production, it is better to keep the worker and scheduler as separate services so they can be restarted independently of the web application.

10. Conclusions and next steps

As a result, Invoice Ninja runs on a VPS in Docker: the application is separated from MySQL and Redis, HTTPS is handled by Caddy, SMTP is responsible for sending documents, and a daily Restic backup protects the database and user files.

Next, you should add monitoring for free space and HTTPS availability, regularly test recovery, and update images during a separate maintenance window. As the load grows, measure queue length, disk I/O, and memory usage; then you can move MySQL or Redis to a separate server, add application replicas, and connect external object storage for files.

Affiliate links: we may earn a commission, your price stays the same.

Was this guide helpful?

Your feedback helps us improve our guides.

Share this post:

Send this guide to someone who may find it useful.

Telegram VKVK WhatsApp Facebook LinkedIn XX

Installing Invoice Ninja on a VPS: Docker, SSL, SMTP, cron, and backups