Docker Compose on a Linux VPS: deploy and maintain a stack in production
Docker Compose describes an application's services, images, networks, volumes and ports in a single file. This guide shows how to deploy a Docker Compose stack in production on a Linux VPS and check it with docker compose ps. It then covers updates, backups and troubleshooting without losing data. Docker must already be installed, as explained in Install Docker on a Linux VPS.
Follow today's Compose conventions
Many examples online still rely on three old habits. Here is what the Docker documentation says about them today.
Leave out the version key
A modern file starts directly with services:. The version property only remains for backward compatibility. According to the Compose Specification, it is purely informative and triggers a warning. Compose always validates the file against the latest schema. Writing version: "3.8" therefore selects no compatibility mode at all.
Type docker compose as two words
The commands in this guide use the Compose plugin built into the Docker CLI.
docker compose up -d
The hyphenated docker-compose command is the old v1 tool, written in Python. Compose v2, announced in 2020, is written in Go and runs as docker compose. Compose v5, released in 2025, behaves like v2 on the command line. Its main addition is an official Go SDK. The numbering jumped straight to 5 to avoid confusion with the old "v2" and "v3" file formats. Either way, type docker compose. The history of Docker Compose covers these versions in detail.
The
docker stack deploycommand belongs to Docker's Swarm mode, which is designed for a group of servers. On a single VPS,docker compose up -dis all you need to deploy the stack.
Name the file compose.yaml
The canonical name is compose.yaml. Compose still reads compose.yml, docker-compose.yaml and docker-compose.yml for older projects. If several of these files sit in the same directory, it picks compose.yaml. The page on the Compose application model recommends this name for any new project.
Understand the stack architecture
Compose does not replace a backup strategy, an update policy or VPS hardening. What it brings is a declarative model. Services, images, networks, volumes, ports and restart policies live in one file that you can review, test and keep under version control. The stack becomes reproducible.
The example in this guide uses the official WordPress and MariaDB images. The same method works for Bitwarden, Pi-hole, Jellyfin, Portainer and most stacks made of an application and a database. The stack follows four rules.
The
appservice is the only one that publishes a port on the VPS.That port only listens on
127.0.0.1. A reverse proxy installed on the VPS thus remains the only public entry point.The
dbservice publishes no port. It can only be reached by its name,db, on the internalbackendnetwork.Two named volumes keep the data when the containers are recreated.
Compose provides internal DNS to services on the same network. The application therefore connects to db:3306, not to a container's IP address. That address changes whenever the container is recreated. Never write it into your configuration.
As for resources, a web application and its database fit on 2 vCPUs and 4 GB of RAM. Plan for more memory if you add a cache, a search engine or other stacks on the same machine. Above all, keep an eye on disk space. Images, volumes and logs pile up faster than you expect.
Prepare the stack directory
A stack needs a known location, tight permissions and a layout that is easy to back up. This block creates the directory, then two random passwords for MariaDB.
# Stack directory, restricted to your account
sudo install -d -m 0750 -o "$USER" -g "$USER" /opt/stacks/wordpress-prod
cd /opt/stacks/wordpress-prod
# Files created with no access for other accounts
umask 077
mkdir -p secrets backups
# Two random passwords for MariaDB
openssl rand -base64 48 > secrets/db_password.txt
openssl rand -base64 48 > secrets/db_root_password.txt
chmod 600 secrets/*.txt
chmod 700 secrets backups
The account that runs Compose must be able to read both files. They stay in plain text on the VPS disk. Compose hands them to the containers as files mounted under /run/secrets. Only the services you authorize receive them, and they do not show up in environment variables. Their source is still a local file that you must protect. This mechanism does not replace a centralized secrets manager. Docker's page on secrets in Compose explains how it works.
Write the compose.yaml file
Create compose.yaml in the stack directory. It starts directly with services:, with no version key. Every setting is commented.
services:
# HTTP service of the application.
app:
# The image reference comes from .env and must be validated before production.
image: "${WORDPRESS_IMAGE:?Set WORDPRESS_IMAGE in .env}"
# Restarts after a reboot, unless an administrator stopped the service on purpose.
restart: unless-stopped
# Avoids zombie processes if the image does not reap them itself.
init: true
# The database must be reported healthy before the application is created.
depends_on:
db:
condition: service_healthy
# Container port 80 listens only on the VPS loopback interface.
ports:
- "${APP_BIND_IP:-127.0.0.1}:${APP_PORT:-8080}:80"
# Non-sensitive values can be interpolated from .env.
environment:
WORDPRESS_DB_HOST: "db:3306"
WORDPRESS_DB_NAME: "${DB_NAME:?Set DB_NAME in .env}"
WORDPRESS_DB_USER: "${DB_USER:?Set DB_USER in .env}"
# The official image can read the password from a file.
WORDPRESS_DB_PASSWORD_FILE: /run/secrets/db_password
# Application content outlives the container.
volumes:
- wordpress_data:/var/www/html
# The application only gets the password it needs.
secrets:
- db_password
# The application receives front-end traffic and talks to the database privately.
networks:
- frontend
- backend
# A local limit stops logs from filling the VPS disk.
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# Gives the HTTP server time to close its connections cleanly.
stop_grace_period: 30s
# Database service, with no port published on the host.
db:
# This image reference is also managed in .env.
image: "${MARIADB_IMAGE:?Set MARIADB_IMAGE in .env}"
# A manual stop is still respected after the daemon or the VPS restarts.
restart: unless-stopped
# Creates the database and the user on the very first start only.
environment:
MARIADB_DATABASE: "${DB_NAME:?Set DB_NAME in .env}"
MARIADB_USER: "${DB_USER:?Set DB_USER in .env}"
MARIADB_PASSWORD_FILE: /run/secrets/db_password
MARIADB_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
# MariaDB data files live in a named volume.
volumes:
- mariadb_data:/var/lib/mysql
# Unlike the application, the database gets both secrets.
secrets:
- db_password
- db_root_password
# This script ships with the official MariaDB image.
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 10
start_period: 30s
# The database only joins the private internal network.
networks:
- backend
# Same local rotation policy as the application.
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# A database may need time to finish its writes.
stop_grace_period: 1m
# Persistent storage managed by Docker.
volumes:
wordpress_data:
mariadb_data:
# The two network zones of the stack.
networks:
frontend:
driver: bridge
backend:
driver: bridge
# Stops this network from providing direct external connectivity.
internal: true
# Each local secret comes from its own file on the host.
secrets:
db_password:
file: ./secrets/db_password.txt
db_root_password:
file: ./secrets/db_root_password.txt
Some behaviors come from the images, not from Compose. The official WordPress image reads the password from the file set in WORDPRESS_DB_PASSWORD_FILE. The official MariaDB image accepts the MARIADB_*_FILE variants and ships the healthcheck.sh script. The MariaDB documentation describes its tests. Before you reuse this model for another application, check what its image supports.
With depends_on and condition: service_healthy, Compose waits for the database health check to pass before it creates the application. The first start is safer. The application still has to reconnect on its own if the database drops later on. The page on startup order covers this point.
Fill in the .env file
Compose automatically reads the .env file next to compose.yaml. It uses it to replace ${VARIABLE} expressions, as described on the page about variable interpolation.
# Stable project name. It affects the actual names of volumes and networks.
COMPOSE_PROJECT_NAME=wordpress-prod
# The service stays local to the VPS and is published by a reverse proxy.
APP_BIND_IP=127.0.0.1
APP_PORT=8080
# Non-sensitive values passed to both services.
DB_NAME=wordpress
DB_USER=wordpress
# Readable tags to prepare the first pull.
# Before going live, replace them with the validated digests, as explained below.
WORDPRESS_IMAGE=wordpress:apache
MARIADB_IMAGE=mariadb:lts
The
MARIADB_*variables only apply on the first start, to an empty data directory. Changing the content of a secret file does not change the password stored in MariaDB.
According to the image documentation, these variables have no effect on an existing database. To change a password, update the account inside the database first. Then update the secret that the application reads. Finally, restart or reload the services as their documentation describes.
Pin images by digest
An image tag can change content. The publisher can point the same tag at a new image. For a reproducible deployment, test the image, then pin its reference with a name@sha256:... digest. An update then becomes a deliberate change that you can review. Docker's best practices recommend this kind of pinning.
These commands return the fixed reference of the images you just tested.
# Pull the images you want to test
docker pull wordpress:apache
docker pull mariadb:lts
# Print their fixed reference, in the form name@sha256:...
docker image inspect wordpress:apache --format '{{index .RepoDigests 0}}'
docker image inspect mariadb:lts --format '{{index .RepoDigests 0}}'
Copy each full result into the matching variable in .env. From then on, docker compose pull no longer swaps content silently. Every update goes through a new digest.
A digest pins the image, not the content of the volume. In this example, the difference matters. According to the WordPress image documentation, WordPress automatic updates then modify the content of /var/www/html. Your update policy must therefore cover both the images and the application's own update mechanism.
Keep .env and secrets out of Git
The example puts no password in .env. Still, do not commit this file. Over time, it often picks up a token, a private URL or a production-only value. A secret written in compose.yaml or .env and pushed to Git stays in the history. Deleting it in the latest commit is not enough.
Create a .gitignore file.
.env
secrets/
backups/
You can commit a .env.example that only holds the variable names and dummy values. Protect the real file.
chmod 600 .env
Be careful with docker compose config without options, too. The command prints the resolved configuration, with the values filled in. A secret passed through a variable shows up in plain text. docker compose config --quiet validates the file without printing anything, according to the docker compose config reference.
Choose between named volumes and bind mounts
A container is disposable. Whatever it writes to its own layer disappears with it. Any data you want to keep must be declared as persistent.
| Criterion | Named volume | Bind mount |
|---|---|---|
| Source | Object managed by Docker | Explicit path on the VPS, for example /srv/app/config |
| Best use | Data produced by the application or the database | Configuration file managed from the host, certificate, content the host edits directly |
| Portability | Loosely tied to the VPS file tree | Depends on the path, the permissions and sometimes the host's SELinux context |
| Main risk | Forgetting that it lives outside the stack directory | Mounting the wrong path, hiding the image content or granting write access too broadly |
| Backup | Must be exported explicitly | Must be included in the backup of the host path |
Docker recommends volumes for data that containers produce. A volume survives the removal of the container that used it. A bind mount is a better fit when an administrator or a host tool must edit a file. For a database, only use a bind mount if you control its owner, permissions, backup and security context.
In this stack, three items are persistent.
The
wordpress_datavolume keeps/var/www/html.The
mariadb_datavolume keeps/var/lib/mysql.The
./secrets/*.txtfiles stay on the host and are mounted separately, only into the authorized services.
Find where a volume really lives
mariadb_data is the logical name of the volume in the Compose model. With COMPOSE_PROJECT_NAME=wordpress-prod, Docker usually creates a volume named wordpress-prod_mariadb_data. Do not build your scripts on that assumption. Compose adds labels to its volumes, and docker volume inspect returns their actual mount point.
# Stack volumes, found by their label
docker volume ls \
--filter label=com.docker.compose.project=wordpress-prod
# Actual name of the database volume
DB_VOLUME="$(docker volume ls \
--filter label=com.docker.compose.project=wordpress-prod \
--filter label=com.docker.compose.volume=mariadb_data \
--format '{{.Name}}')"
# Actual mount point on the VPS
docker volume inspect "$DB_VOLUME" --format '{{.Mountpoint}}'
With the local driver and a Docker daemon running as root, this path is often under /var/lib/docker/volumes/. That is not guaranteed. Rootless mode, a custom data-root or a remote driver all move it. Only the output of docker volume inspect is authoritative. Never edit a database's internal files in that directory by hand.
Avoid the commands that delete data
docker compose down removes the stack's containers and networks. By default, it keeps named volumes. The -v option deletes them as well, according to the docker compose down reference.
Never use
docker compose down -vto update or troubleshoot a stack. Before you delete a volume on purpose, make sure you have a backup you can restore.
Be careful with docker volume prune as well. Without options, it now only removes unused anonymous volumes. With --all (or -a), it also deletes named volumes that no container uses anymore. A production volume becomes "unused" as soon as its container is removed, even if its data is still essential. Removing a container does not back up its volume either.
Publish ports locally
These two forms are not equivalent.
# Published on every address of the VPS
ports:
- "8080:80"
Without a host address, Docker publishes the port on every address of the VPS, over IPv4 and IPv6. The service can then become reachable from the internet, if routing and network rules allow it.
# Published on the loopback interface only
ports:
- "127.0.0.1:8080:80"
Here, the port only listens on the IPv4 loopback interface. This is the right choice when Nginx or Apache runs on the VPS and forwards requests to http://127.0.0.1:8080. Only the VPS can then reach the port, according to the page on port publishing. The same page notes that before Docker Engine 28.0, a machine on the same network segment could reach a port bound to 127.0.0.1. Keep Docker up to date.
Check the actual result instead of just rereading the YAML.
# Container state and published ports
docker compose ps
# Address port 8080 actually listens on
ss -lntp | grep ':8080'
# Local HTTP response
curl --fail --head http://127.0.0.1:8080
The database has no ports section. The expose directive is not needed for app to reach db on the same Compose network. So never publish 3306:3306 when only the application needs to talk to the database.
Docker writes its own firewall rules. A published port bypasses UFW rules and stays reachable, even if
ufw statusshows it as blocked.
The guide How to set up the UFW firewall on Ubuntu or Debian explains this trap and how to fix it. Three rules are enough to avoid it. Only publish what needs to be published. Bind the port to 127.0.0.1 behind a local proxy. Then check what is actually listening.
If the reverse proxy itself runs in a container, 127.0.0.1 points to that container, not to the VPS or the application. In that case, connect the proxy and the application through a shared Docker network, without publishing the application port to the internet. For a proxy installed on the VPS, follow Host multiple websites on a VPS with Nginx. The guide Certbot: install a Let's Encrypt SSL certificate on a VPS then adds HTTPS.
Choose a restart policy
The always and unless-stopped policies restart a container that stops, and again when the Docker daemon comes back. They differ after a manual stop.
alwaysrestarts a manually stopped container as soon as the Docker daemon restarts.unless-stoppedrespects that manual stop, even after the daemon or the VPS restarts.
For a stack you manage by hand, unless-stopped keeps a service stopped for maintenance from coming back at the next reboot. always fits when the service must come back no matter what. Neither one replaces a health check. Both react to the main process exiting, not to an application that is stuck but still alive. A running container is therefore no proof of a healthy application. The page on restart policies describes all four policies.
Validate and start the stack
Check the CLI first.
docker compose version
docker info
Then validate and deploy from the stack directory.
cd /opt/stacks/wordpress-prod
# Validate the file without printing it
docker compose config --quiet
# Pull the images, then create the containers in the background
docker compose pull
docker compose up -d
# Check the state, then read the latest logs
docker compose ps
docker compose logs --tail=100 --timestamps
docker compose pull downloads the images without touching the running containers. docker compose up -d then compares the desired state with the current one. It creates what is missing and recreates the services whose image or configuration changed. Mounted volumes are preserved during this recreation, according to the docker compose up reference.
A successful test on the VPS does not prove that port 8080 is closed to the public. After the first start, also check exposure from another machine. From your computer, curl -m 5 http://203.0.113.10:8080 should fail, with the VPS main IP in place of this sample address.
Read the output of docker compose ps
docker compose ps lists the containers of the stack. By default, it only shows running ones. Add --all (or -a) to see stopped containers too.
The
STATUScolumn showsUpwhen the container is running. Fordb, which has a health check, it adds(health: starting)during startup, then(healthy).Restarting,Exitedor(unhealthy)point to a problem. The section on restart loops further down helps you find it.The
PORTScolumn forappshould show127.0.0.1:8080->80/tcp. The one fordbmust not contain any address followed by an->arrow.
The -q option only prints container IDs, which comes in handy in a script. The docker compose ps documentation lists the other options.
Update without losing data
In production, an update follows a short procedure. It is not a command you run blindly.
Before the update
Read the release notes of the application and the database. Look for migrations and supported upgrade paths.
Check disk space and inodes with
df -handdf -i.Take a backup and copy it off the VPS. Test restoring it on a regular basis.
Write down the image references currently deployed with
docker compose images.Change the tags or digests in
.envonly once they are validated.Run
docker compose config --quiet.If downtime is possible, warn the users of the service.
Apply the update
cd /opt/stacks/wordpress-prod
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --since=10m --timestamps
Compose may recreate three things.
The
appcontainer, if its image reference or configuration changes.The
dbcontainer, in the same cases.The networks whose definition changed.
It keeps everything else.
The content of the
wordpress_dataandmariadb_datanamed volumes.The VPS files used as bind mounts or as secret sources.
The previous images, as long as you do not delete them.
docker compose restart is not enough after you edit compose.yaml or the variables. It restarts the existing containers without applying the new configuration, as the docker compose restart reference points out. Use docker compose up -d.
Recreating a container can cause a brief interruption. Compose on a single VPS does not promise zero-downtime updates. For a critical application, plan an approach suited to the application, another instance or an orchestration platform.
Roll back
To go back to the previous version, put the old image reference back in .env. Then run docker compose pull and docker compose up -d again. This does not undo a schema migration. If the new version changed the database in an incompatible way, two options remain. Follow the rollback plan provided by the publisher, or restore a validated backup. That is why the backup comes before the update.
Back up the stack and its data
Copying compose.yaml backs up none of the data in the volumes. Copying MariaDB's internal files while it runs does not guarantee a consistent database either. For this stack, a complete backup combines five items.
A logical dump of MariaDB, produced by the database's own tool.
An archive of the application volume, taken while the application is stopped.
A copy of
compose.yaml,.envand the list of image references.A separate, encrypted backup of the secret files.
A copy off the VPS, with a retention period and restore tests.
MariaDB documents mariadb-dump in its container backup guide.
Run a consistent backup
Run this block with Bash from the stack directory. The application is stopped to block writes during the dump and the archive. The database stays up for the logical dump. The trap restarts the application even if a command fails.
set -Eeuo pipefail
cd /opt/stacks/wordpress-prod
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
DEST="backups/$STAMP"
install -d -m 0700 "$DEST"
# Validate, then stop the application. The trap starts it again whatever happens.
docker compose config --quiet
docker compose stop app
trap 'docker compose start app' EXIT
# Compressed logical dump of the database
docker compose exec -T db sh -c '
exec mariadb-dump \
--user=root \
--password="$(cat /run/secrets/db_root_password)" \
--single-transaction \
--routines \
--triggers \
--events \
"$MARIADB_DATABASE"
' | gzip -9 > "$DEST/database.sql.gz"
# Archive of the application volume
docker compose run --rm --no-deps -T \
--entrypoint tar app \
-C /var/www/html -czf - . \
> "$DEST/wordpress-data.tar.gz"
# Configuration and image references
cp compose.yaml .env "$DEST/"
docker compose images > "$DEST/images.txt"
# Archive checks and SHA-256 checksums
gzip -t "$DEST/database.sql.gz"
tar -tzf "$DEST/wordpress-data.tar.gz" > /dev/null
(cd "$DEST" && sha256sum database.sql.gz wordpress-data.tar.gz compose.yaml .env images.txt > SHA256SUMS)
docker compose start app
trap - EXIT
This script deliberately leaves secrets/ out of the archive. Export those files to a vault or an encrypted backup, with separate access control. A backup that stays on the same VPS disappears with the disk, the account or the incident that takes down production. To send the backups/ directory to remote storage, follow Rclone: cloud synchronization on a Linux VPS.
A dump with --single-transaction suits transactional tables. An application that uses other engines, or several storage systems, needs a procedure from its publisher. For large volumes and strict recovery targets, also look at physical backups, replication and coordinated snapshots.
Add automatic VPS backups
Would you rather not script and monitor this chain yourself? Automatic backups are a paid option for the VPS. This option makes a full copy of the server every night and stores it outside the server. You choose how many copies to keep. You start a restore from the Backups tab of the VPS page. The guide How to set up automatic VPS backups explains how to add it.
Restoring one of these copies replaces the whole VPS disk. So keep the database dump as well, since it lets you recover the data alone. The option does not spare you from testing an application restore either.
Test a restore
A backup you have never restored is only a hypothesis. Run the test in a separate project, with empty volumes and the same image references as the backup.
Copy
compose.yaml,.envand test secrets to another VPS or another directory.Change
COMPOSE_PROJECT_NAMEand the host port so that production stays untouched.Create the application volume with a one-off command that extracts the archive.
Start only
dband wait for thehealthystate. Then import the dump into the empty database.Start
appwithdocker compose up -d app. Test the application's features and note the actual recovery time.
Steps 3 and 4 take two commands. Replace DATE with the name of the backup directory.
# Step 3. Recreate the application volume from the archive
docker compose run --rm --no-deps -T \
--entrypoint tar app \
-C /var/www/html -xzf - \
< backups/DATE/wordpress-data.tar.gz
# Step 4. Start only the database and wait until it is healthy
docker compose up -d --wait db
Then import the dump into the test database, already initialized and empty.
gzip -dc backups/DATE/database.sql.gz | \
docker compose exec -T db sh -c '
exec mariadb \
--user=root \
--password="$(cat /run/secrets/db_root_password)" \
"$MARIADB_DATABASE"
'
Do not run these commands on the production stack. A full restore procedure states how to get an empty database, how much downtime is acceptable and how to roll back if validation fails.
Diagnose a restart loop
The reflex to avoid is running docker compose down right away. The command removes the containers, and part of the state information with them. Start by observing.
# All containers, including stopped ones
docker compose ps --all
# Latest logs of each service
docker compose logs --tail=200 --timestamps app
docker compose logs --tail=200 --timestamps db
# Follow the logs live, Ctrl+C to exit
docker compose logs --follow --since=10m app
logs filters by service, follows the stream with --follow and limits history with --tail or --since. The docker compose logs reference lists the other options.
Next, inspect the exact state of the container and the VPS resources.
# State, exit code, out-of-memory kill and restart count
CID="$(docker compose ps -q app)"
docker inspect "$CID" --format \
'status={{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}} error={{.State.Error}}'
# Processes, usage and VPS resources
docker compose top
docker stats --no-stream
df -h
df -i
free -h
# Docker daemon log
journalctl -u docker --since '30 minutes ago'
The most common causes are the following.
A secret that is missing, unreadable or mounted under the wrong name.
A database that is not ready yet, mismatched credentials or a failed migration.
A host port that is already in use.
A volume mounted in the wrong place, or permissions that do not match the container user.
A process killed for lack of memory, visible as
oom=true.A full disk or exhausted inodes.
An image built for another architecture than the VPS.
An interpolated configuration that differs from what you expected.
Validate the model without printing the values, then list the expected variables.
docker compose config --quiet
docker compose config --variables
If the service restarts too fast for exec, start a one-off container without its dependencies, with a shell. The image must include one.
docker compose run --rm --no-deps --entrypoint sh app
This one-off container mounts the same volumes and secrets as the service. Change nothing until you understand the cause.
The json-file rotation set in the file limits the space taken by logs. According to the json-file logging driver documentation, max-size defaults to -1, which means no size limit. For a large production setup, also ship logs to an external system with suitable retention.
Keep an operations routine
After every change
docker compose config --quiet
docker compose up -d
docker compose ps
docker compose logs --since=10m --timestamps
After every VPS reboot
docker compose ps
docker compose logs --since=30m --timestamps
ss -lntp
Check that the application is healthy and that the database is not published. The application port must stay bound to 127.0.0.1, and the reverse proxy must serve the domain over HTTPS.
For the rest of server security, from SSH to system updates, follow Secure a Linux VPS.
Need help?
Open a ticket from Tickets › Open a Ticket, or from the Contact support tile at the bottom of the VPS page. You can also ask your question on the OuiHeberg Discord.
Root access, your choice of distribution and management from the OuiHeberg client area.
View plans →