VPS Tutorials
RabbitMQ on a VPS: TLS, least privilege and message recovery
Deploy RabbitMQ with Compose, private AMQPS and Caddy management HTTPS. Correct certificate permissions, verify hostnames, configure application users and reliable delivery, and recover definitions and messages with suitable backups.

Putting payment callbacks, order processing, email and AI jobs inside one HTTP request makes the endpoint depend on every downstream service. RabbitMQ separates producers from consumers: applications publish messages, workers process them asynchronously, and acknowledgments, retries and dead-letter queues handle failures.
This Ubuntu 24.04, Docker Compose and Caddy walkthrough originally used RabbitMQ 4.3.5, checked on September 15, 2026. The official latest release checked on November 16 is 4.4.0. The pinned 4.3.5 definition below remains a version-specific example; for a fresh installation review the current release and use its pinned management image. Existing deployments must follow the supported upgrade path instead of assuming that changing the tag is safe.
RabbitMQ is a message broker, not a database or a scheduling dashboard:
- Publish from web requests; process email, images and reports in workers.
- Separate order, inventory and payment services through exchanges and queues.
- Combine acknowledgments, publisher confirms and dead-letter exchanges for failure handling.
- Scale competing consumers to share a queue's work.
- Integrate AMQP 0-9-1, AMQP 1.0, MQTT, STOMP or Stream clients, enabling the relevant plugins.
- Observe connections, backlog, throughput and resource alarms through the UI, HTTP API and Prometheus.
For a script every minute, cron or a systemd timer is simpler. For long-lived event streams and replayable logs, consider Kafka. RabbitMQ is particularly useful for routed business tasks, responsive delivery and application-level acknowledgment.
| Architecture | Benefit | Limitation | Appropriate use |
|---|---|---|---|
| One RabbitMQ node | Simple deployment, lower cost and direct troubleshooting | Host or disk failure interrupts service | Development, low-risk work and acceptable recovery downtime |
| Several containers on one VPS | Can test multiple nodes | Shared host, disk and network failure domain | Laboratory testing, not production HA |
| Three independent nodes with quorum queues | Can tolerate one failed member with a majority available | Higher cost and operational complexity | Critical workloads requiring host-failure tolerance |
Use odd membership for quorum replication, typically 3 or 5. Two members cannot provide useful majority-based single-member failure tolerance. Check the actual replica membership of each quorum queue: having three brokers alone does not ensure every queue has three replicas.
This guide covers a recoverable single node with a stable node name. For critical infrastructure, move to independent failure domains rather than adding containers to the same host.
Capacity depends on connections, channels, queue count, message size, backlog duration, acknowledgment behavior and storage latency.
| Workload | Suggested VPS | Assumption |
|---|---|---|
| Development | 2 vCPU, 2GB RAM, 30GB SSD | No important backlog; downtime acceptable |
| Small production, short messages | 2–4 vCPU, 4GB RAM, 60GB NVMe | Leave memory for the broker, cache and monitoring |
| Many connections or long backlogs | 4 vCPU, at least 8GB RAM, dedicated NVMe | Test message size, confirm latency and disk throughput |
| Port | Purpose | Exposure |
|---|---|---|
5671/TCP | AMQP over TLS | Loopback by default; a private IP for remote clients |
5672/TCP | Plaintext AMQP | Disabled |
15672/TCP | Management UI/API | 127.0.0.1 behind Caddy HTTPS |
15692/TCP | Prometheus | 127.0.0.1 |
4369/TCP | epmd | Not published |
25672/TCP | Inter-node traffic | Unpublished here; private node network in a cluster |
Do not publish 5672, 15672, 4369 or 25672 to the internet. Docker port publication can bypass some host-firewall rules. Remote AMQP needs a specific private binding, source-restricted cloud rules and TLS; see protecting database and middleware access.
Install Docker Engine and Compose v2 from the official Ubuntu repository instructions first. The following block installs Caddy and tools, then checks the existing Docker installation:
sudo apt update
sudo apt full-upgrade -y
sudo apt install -y ca-certificates curl openssl caddy
docker --version
docker compose version
sudo systemctl enable --now caddy
Plan package upgrades/reboots, log limits, health checks and recovery using the Compose production checklist.
sudo install -d -m 0750 -o "$USER" -g "$USER" /opt/rabbitmq
cd /opt/rabbitmq
install -d -m 0750 data tls
install -d -m 0700 pki backups
umask 077
Create .env. Keep AMQPS on loopback; use a WireGuard or other private interface for remote consumers:
{
printf 'RABBITMQ_ADMIN_USER=opsadmin\n'
printf 'RABBITMQ_ADMIN_PASS=%s\n' "$(openssl rand -hex 32)"
printf 'RABBITMQ_DEFAULT_VHOST=production\n'
printf 'RABBITMQ_BIND_IP=127.0.0.1\n'
} > .env
chmod 600 .env
This overwrites the environment file and is only for a new instance. Keep .env and connection strings out of Git, logs and support tickets. Default-user variables initialize an empty data directory only; editing .env later does not rotate an existing account.
Generate an internal CA and a server certificate for mq.example.com:
cd /opt/rabbitmq/pki
openssl genrsa -out ca.key 4096
openssl req -x509 -new -sha256 -days 3650 \
-key ca.key \
-subj '/CN=RabbitMQ Internal CA' \
-out ca.crt
openssl genrsa -out server.key 4096
openssl req -new -sha256 \
-key server.key \
-subj '/CN=mq.example.com' \
-out server.csr
printf '%s\n' \
'subjectAltName=DNS:mq.example.com' \
'extendedKeyUsage=serverAuth' > server.ext
openssl x509 -req -sha256 -days 825 \
-in server.csr \
-CA ca.crt \
-CAkey ca.key \
-CAcreateserial \
-extfile server.ext \
-out server.crt
install -m 0644 ca.crt server.crt /opt/rabbitmq/tls/
install -m 0600 server.key /opt/rabbitmq/tls/
Keep ca.key offline or encrypted; never mount it in the broker or distribute it to clients. Clients trust ca.crt. Replace the example hostname in both the certificate subject and SAN. An enterprise CA is also suitable, provided the SAN matches the client hostname. Track certificate expiry and rehearse renewal.
Create /opt/rabbitmq/rabbitmq.conf:
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /etc/rabbitmq/tls/ca.crt
ssl_options.certfile = /etc/rabbitmq/tls/server.crt
ssl_options.keyfile = /etc/rabbitmq/tls/server.key
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = false
management.tcp.ip = 0.0.0.0
management.tcp.port = 15672
prometheus.tcp.ip = 0.0.0.0
prometheus.tcp.port = 15692
vm_memory_high_watermark.relative = 0.5
disk_free_limit.absolute = 2GB
Plaintext AMQP is disabled; port 5671 uses TLS. verify_peer validates a presented client certificate, while fail_if_no_peer_cert=false permits TLS clients without a certificate to use username/password authentication. For required mutual TLS, issue client certificates and change the setting to true after compatibility testing.
The current documented default memory watermark is approximately 60% of detected available memory; this example selects 50%. Verify what memory RabbitMQ detects inside its container. The 2GB container limit is separate from the VPS RAM budget, and the watermark is an alarm rather than a hard memory cap. Tune disk_free_limit to backlog size and disk capacity; 2GB free is only a starting threshold.
Create /opt/rabbitmq/enabled_plugins to enable management and Prometheus:
[rabbitmq_management,rabbitmq_prometheus].
Create /opt/rabbitmq/compose.yml:
services:
rabbitmq:
image: rabbitmq:4.3.5-management
container_name: rabbitmq
hostname: rabbitmq-1
restart: unless-stopped
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_ADMIN_USER}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_ADMIN_PASS}
RABBITMQ_DEFAULT_VHOST: ${RABBITMQ_DEFAULT_VHOST}
ports:
- "${RABBITMQ_BIND_IP:-127.0.0.1}:5671:5671"
- "127.0.0.1:15672:15672"
- "127.0.0.1:15692:15692"
volumes:
- ./data:/var/lib/rabbitmq
- ./rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
- ./enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
- ./tls:/etc/rabbitmq/tls:ro
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 30s
timeout: 10s
retries: 5
start_period: 40s
mem_limit: 2g
cpus: 2.0
ulimits:
nofile:
soft: 65536
hard: 65536
logging:
driver: json-file
options:
max-size: "10m"
max-file: "5"
Preserve hostname: rabbitmq-1: the node identity matters for restoring data, particularly quorum queues and streams. Avoid latest tags.
For a fresh deployment of the checked 4.4.0 release, place this in compose.override.yml after reviewing its release notes. Do not apply it blindly to an existing 4.3 instance:
services:
rabbitmq:
image: rabbitmq:4.4.0-management
Before starting, give the selected image's RabbitMQ user access to the mounted files. The generated private key and configuration are otherwise owned by the host user and may be unreadable after the image drops privileges:
cd /opt/rabbitmq
RABBITMQ_SELECTED_IMAGE="$(docker compose config --images)"
RABBITMQ_CONTAINER_UID="$(docker run --rm --entrypoint id "$RABBITMQ_SELECTED_IMAGE" -u rabbitmq)"
RABBITMQ_CONTAINER_GID="$(docker run --rm --entrypoint id "$RABBITMQ_SELECTED_IMAGE" -g rabbitmq)"
sudo chown -R "$RABBITMQ_CONTAINER_UID:$RABBITMQ_CONTAINER_GID" data tls
sudo chmod 750 data tls
sudo chmod 600 tls/server.key
sudo chown "root:$RABBITMQ_CONTAINER_GID" rabbitmq.conf enabled_plugins
sudo chmod 640 rabbitmq.conf enabled_plugins
unset RABBITMQ_SELECTED_IMAGE RABBITMQ_CONTAINER_UID RABBITMQ_CONTAINER_GID
The image-selection command assumes this Compose project has only the broker service. Keep the CA private-key directory outside the container mounts. Validate without printing expanded secrets:
cd /opt/rabbitmq
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose ps
cd /opt/rabbitmq
docker compose exec rabbitmq rabbitmq-diagnostics -q ping
docker compose exec rabbitmq rabbitmq-diagnostics -q listeners
docker compose exec rabbitmq rabbitmq-diagnostics -q check_local_alarms
docker compose logs --tail=200 rabbitmq
Check the server's certificate chain:
openssl s_client \
-connect 127.0.0.1:5671 \
-servername mq.example.com \
-CAfile /opt/rabbitmq/tls/ca.crt \
-verify_return_error </dev/null
Expect Verify return code: 0 (ok), but note that setting SNI with -servername alone does not verify the hostname. Also run:
openssl s_client -connect 127.0.0.1:5671 -servername mq.example.com \
-verify_hostname mq.example.com -verify_return_error \
-CAfile /opt/rabbitmq/tls/ca.crt </dev/null
Use the actual certificate hostname. Then check metrics:
curl -fsS http://127.0.0.1:15692/metrics | head
Alert on node availability, connections, unacknowledged/ready messages, publish/consume rates and memory/disk alarms. For persistent monitoring, see Prometheus and Grafana.
Use a separate domain such as mq-admin.example.com and edit /etc/caddy/Caddyfile:
mq-admin.example.com {
encode zstd gzip
reverse_proxy 127.0.0.1:15672
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
}
}
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
curl -fsSI https://mq-admin.example.com/
Caddy provides management HTTPS; it does not proxy AMQP. Restrict administration to VPN, zero-trust access or approved source IPs, use strong credentials and install security patches. Apply HSTS subdomain coverage only where all affected subdomains support HTTPS. See the Caddy HTTPS guide.
Keep administrator credentials out of applications. Create separate, rotatable users and vhosts per environment or service. This user accesses production and resources beginning with app.:
cd /opt/rabbitmq
APP_USER=worker
APP_PASS="$(openssl rand -hex 32)"
docker compose exec rabbitmq rabbitmqctl add_user "$APP_USER" "$APP_PASS"
docker compose exec rabbitmq rabbitmqctl set_permissions \
-p production "$APP_USER" '^app\.' '^app\.' '^app\.'
install -m 0600 /dev/null app-client.env
printf 'RABBITMQ_USER=%s\nRABBITMQ_PASSWORD=%s\n' \
"$APP_USER" "$APP_PASS" > app-client.env
unset APP_USER APP_PASS
The permission regexes are configure, write and read, in that order. Queues/exchanges must begin with app.. Refine the expressions for the client's actual declarations rather than granting .*. The empty-name default exchange does not match this prefix; explicitly account for it only if the application needs it. Topic routing-key restrictions require topic permissions separately.
Application users need none of the administrator, monitoring or management tags. Connect using amqps://, trust the CA and store the password in restricted configuration or a secret manager. Percent-encode URI-reserved password characters; hex passwords simplify escaping.
- Mark messages persistent.
- Enable publisher confirms and handle negative confirms and timeouts.
- Acknowledge only after business processing; choose explicit requeue/dead-letter behavior on failure.
- Set prefetch to limit outstanding deliveries per consumer.
- Define retry limits, TTL and dead-letter policy.
- Use business idempotency keys to prevent duplicate charges or fulfillment.
Persistence and acknowledgments do not eliminate duplicate processing. Design for at-least-once delivery and idempotent consumers, and test reconnect/backlog recovery under real failures.
Definitions contain users, vhosts, permissions, policies and topology, not pending queue messages. Export them from a running node:
cd /opt/rabbitmq
BACKUP_DIR="backups/$(date -u +%Y%m%dT%H%M%SZ)"
install -d -m 0700 "$BACKUP_DIR"
docker compose exec rabbitmq rabbitmqctl export_definitions \
/var/lib/rabbitmq/definitions-backup.json
docker compose cp \
rabbitmq:/var/lib/rabbitmq/definitions-backup.json \
"$BACKUP_DIR/definitions.json"
docker compose exec rabbitmq rm -f \
/var/lib/rabbitmq/definitions-backup.json
test -s "$BACKUP_DIR/definitions.json"
chmod 600 "$BACKUP_DIR/definitions.json"
They contain password hashes and remain sensitive. On a prepared replacement node, copy the saved definitions file into the working directory before using:
docker compose cp definitions.json \
rabbitmq:/var/lib/rabbitmq/definitions-restore.json
docker compose exec rabbitmq rabbitmqctl import_definitions \
/var/lib/rabbitmq/definitions-restore.json
Importing definitions is not message recovery and can merge with existing topology. Use an isolated target and remove the temporary restore file afterward.
For message data, pause producers and consumers, then stop the node before copying its complete data directory:
cd /opt/rabbitmq
FULL_BACKUP="backups/rabbitmq-full-$(date -u +%Y%m%dT%H%M%SZ).tar.gz"
docker compose stop rabbitmq
sudo tar -czf "$FULL_BACKUP" \
data .env compose.yml rabbitmq.conf enabled_plugins tls pki
sudo chown "$USER":"$USER" "$FULL_BACKUP"
chmod 600 "$FULL_BACKUP"
docker compose start rabbitmq
test -s "$FULL_BACKUP"
docker compose exec rabbitmq rabbitmq-diagnostics -q ping
Check the archive operation succeeded before treating it as a backup. Encrypt the archive, especially because it includes credentials and CA material, and keep the CA-key copy separately controlled. Copy backups off-host.
Restore a stopped, isolated compatible instance with the same rabbit@rabbitmq-1, complete data including the Erlang cookie, and correct ownership. Restore configuration/certificates, start the node, verify topology and backlog, and reconnect test clients before production traffic. Never initialize, overwrite or rename a live production data directory as a restore test.
Review target release notes, supported version transitions, feature flags and Erlang compatibility. Complete both definitions and stopped-node backups first. The official image includes its runtime, but that does not remove upgrade compatibility requirements.
cd /opt/rabbitmq
docker compose exec rabbitmq rabbitmqctl await_startup
docker compose exec rabbitmq rabbitmqctl export_definitions \
/var/lib/rabbitmq/pre-upgrade-definitions.json
# 修改 compose.yml 中固定的镜像补丁版本后再执行
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose exec rabbitmq rabbitmqctl await_startup
docker compose exec rabbitmq rabbitmq-diagnostics -q ping
docker compose exec rabbitmq rabbitmq-diagnostics -q check_local_alarms
docker compose logs --tail=200 rabbitmq
The example exports another definitions copy inside the data directory; copy it off-container if retaining it. Change the pinned image or override before pulling. A single node has downtime.
For independent clusters, follow the documented rolling order and replica availability checks. Verify publisher confirms, consumer acknowledgments, decreasing backlog, management API and metrics rather than only container startup. After irreversible changes, recover a compatible pre-upgrade snapshot rather than simply downgrading the image.
ss -lnt | grep ':5671'
docker compose ps
docker compose exec rabbitmq rabbitmq-diagnostics -q listeners
openssl s_client -connect 127.0.0.1:5671 \
-servername mq.example.com \
-CAfile tls/ca.crt </dev/null
If local access works, inspect RABBITMQ_BIND_IP, private routes, security groups and Docker publication using the port/firewall troubleshooting guide. Do not switch to public plaintext 5672.
Match the client DNS name to the SAN and trusted CA. Correct private DNS, certificate SAN, system time and CA paths instead of disabling validation.
docker compose exec rabbitmq rabbitmqctl list_users
docker compose exec rabbitmq rabbitmqctl list_vhosts
docker compose exec rabbitmq rabbitmqctl list_permissions -p production
Check user credentials and all permission categories. URI-encode the vhost: the default / is usually %2F; this guide uses production as /production.
docker compose exec rabbitmq rabbitmq-diagnostics -q check_local_alarms
docker stats rabbitmq --no-stream
df -h /opt/rabbitmq/data
du -sh /opt/rabbitmq/data
Memory/disk alarms block publishing to protect the node. Reduce backlog, restore consumers, increase storage and investigate large messages before raising thresholds.
Development can start at 2 vCPU/2GB; small production commonly needs 2–4 vCPU, 4GB and 60GB NVMe. Test connections, message size, queues, backlog and confirms with your actual workload.
Avoid it. Disable plaintext AMQP; keep management on loopback behind HTTPS. Remote applications should use private/VPN access, TLS 5671 and source restrictions.
Durability retains queue definitions. Messages also require persistence and publisher confirms, while consumers must acknowledge correctly; failures can still create uncertain delivery or duplication.
Yes, without host-failure tolerance. Useful single-node-failure tolerance requires at least three independent members and an available majority.
No. They preserve accounts and topology; pending messages require a consistent stopped-node data backup.
Defaults only initialize empty storage. Use rabbitmqctl change_password or the API, update application secrets and verify reconnection.