Skip to content
NevaraCloud

Deployment

Running PostgreSQL, MySQL and Redis for your app in production

By , FounderUpdated 11 min read

Same stack as the app, or a separate database server?

For most small and medium apps, the simplest setup that works is the database running as a container in the same Docker Compose stack as the app, on the same server. You get one file that describes everything, no network hop between app and database, and one place to back up. The cost is that app and database share CPU, memory and disk, and if that server goes down, both go down.

Database in the app's stackManaged or separate database server
SetupOne compose.yaml, one serverTwo things to configure, connect and secure
LatencyLowest: same machineLow if same data centre, noticeable if not
IsolationA busy app can starve the databaseDatabase has its own resources
ScalingScale the whole server upScale app servers and database separately
Who does backups, upgrades, failoverYouUsually the provider, depending on the service

Move the database out when you run more than one app server, when the database needs more memory than you can give it alongside the app, or when you need a standby replica. Wherever it runs, keep it in the same data centre as the app. Every query is a round trip, and a page that makes thirty queries pays that cost thirty times. If your users are in Sri Lanka and your app is hosted near them, a database on another continent undoes the benefit.

PostgreSQL or MySQL? Both are solid. Pick the one your framework and ORM support best and that you know how to operate: Django, Prisma and most new Node.js projects lean PostgreSQL; Laravel and many PHP apps grew up on MySQL. Don't run both unless an app you can't change needs the other one. Two databases means two sets of backups, upgrades and tuning.

A compose.yaml for PostgreSQL (or MySQL) and Redis

This builds on our Docker production checklist, which covers the app and reverse proxy side. Here is the data side: pinned images, named volumes, healthchecks and memory limits.

compose.yaml (data services)
services:
  db:
    image: postgres:17-alpine
    restart: unless-stopped
    env_file: ./db.env
    command:
      - postgres
      - -c
      - shared_buffers=256MB
      - -c
      - max_connections=100
      - -c
      - log_min_duration_statement=500
    shm_size: 256mb
    volumes:
      - pgdata:/var/lib/postgresql/data
    networks: [backend]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
      interval: 10s
      timeout: 5s
      retries: 5
    deploy:
      resources:
        limits:
          memory: 1G

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    env_file: ./redis.env
    command: ["sh", "-c", "exec redis-server /usr/local/etc/redis/redis.conf --requirepass \"$$REDIS_PASSWORD\""]
    volumes:
      - ./redis.conf:/usr/local/etc/redis/redis.conf:ro
      - redisdata:/data
    networks: [backend]
    healthcheck:
      test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"]
      interval: 10s
      timeout: 5s
      retries: 5
    deploy:
      resources:
        limits:
          memory: 384M

networks:
  backend:
    internal: true

volumes:
  pgdata:
  redisdata:

Your app service joins the backend network and connects to hosts db and redis. The $$ stops Compose from substituting the variables, so the shell inside the container fills them in from the env file. shm_size matters for PostgreSQL: Docker's default 64 MB of shared memory can cause "could not resize shared memory segment" errors on parallel queries.

If your app uses MySQL instead, swap the db service for this:

compose.yaml (MySQL alternative)
db:
    image: mysql:8.4
    restart: unless-stopped
    env_file: ./db.env
    command:
      - --innodb-buffer-pool-size=512M
      - --max-connections=100
      - --slow-query-log=ON
      - --long-query-time=1
    volumes:
      - mysqldata:/var/lib/mysql
    networks: [backend]
    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 --silent"]
      interval: 10s
      timeout: 5s
      retries: 10
      start_period: 30s
    deploy:
      resources:
        limits:
          memory: 1G

The -h 127.0.0.1 is deliberate. On first start the image runs a temporary server with networking off while it creates your database; checking over TCP means the container only reports healthy once the real server is up. Add mysqldata: under volumes:.

db.env (PostgreSQL) — chmod 600, never commit
POSTGRES_USER=postgres
POSTGRES_PASSWORD=a-long-random-admin-password
POSTGRES_DB=app
redis.env — chmod 600, never commit
REDIS_PASSWORD=another-long-random-password

For MySQL the variables are MYSQL_ROOT_PASSWORD and MYSQL_DATABASE. Generate passwords with openssl rand -base64 32. Both official images also read _FILE variants (POSTGRES_PASSWORD_FILE, MYSQL_ROOT_PASSWORD_FILE) if you prefer Compose secrets: over env files.

Keep databases off the internet and give the app its own user

None of the data services above has a ports: section, and that is the most important line in this guide. Never publish 5432, 3306 or 6379 to the internet. Automated scanners look for exactly these ports, and Docker's published ports bypass ufw, so a firewall rule will not save you. If you need to connect from your laptop, use an SSH tunnel to a port bound to 127.0.0.1, as shown in the server security checklist.

Redis was built to sit on a trusted network, not the internet. An exposed Redis with no password can be used to read your data, wipe it or write files on the server. Its protected-mode only blocks outside connections when no password is set and no bind address is configured; don't rely on it inside Docker. Use a password, an internal network and no published port.

The admin user from the env file is a superuser. Your app should not connect with it. In PostgreSQL, a clean split is an owner role that runs migrations and an app role that can only read and write data. Connect with docker compose exec db psql -U postgres -d app and run:

psql (as postgres, in database app)
CREATE ROLE app_owner LOGIN PASSWORD 'change-me-owner';
CREATE ROLE app_user  LOGIN PASSWORD 'change-me-user';

ALTER DATABASE app OWNER TO app_owner;
REVOKE ALL ON DATABASE app FROM PUBLIC;
GRANT CONNECT ON DATABASE app TO app_user;

GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_user;

-- Tables that app_owner creates later get the same grants automatically
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO app_user;

Run migrations with app_owner and the app with app_user. From PostgreSQL 15 on, ordinary users can no longer create tables in public by default; the database owner can, which is why ownership moves to app_owner. The MySQL equivalent:

mysql (as root)
CREATE USER 'app_owner'@'%' IDENTIFIED BY 'change-me-owner';
CREATE USER 'app_user'@'%'  IDENTIFIED BY 'change-me-user';

GRANT ALL PRIVILEGES ON app.* TO 'app_owner'@'%';
GRANT SELECT, INSERT, UPDATE, DELETE ON app.* TO 'app_user'@'%';

'%' means any host, which is acceptable here only because the database is on an internal Docker network. If your ORM runs migrations on app startup and you can't change that, the app needs the owner's rights; it's a trade-off, so at least keep it off the superuser. Keep these SQL scripts in your repo (without the real passwords) so you can recreate users after a restore.

For Redis, requirepass is the baseline. If several apps share one Redis, Redis 6+ ACLs let you give each its own user and key prefix (ACL SETUSER or user lines in the config). Test your client library after restricting commands; queue libraries often call commands like INFO.

Starting points for memory and connections

These are starting points to adjust after watching real usage, not guarantees of performance.

  • PostgreSQL shared_buffers: about 25% of the memory the database is allowed, so 256MB under a 1 GB limit. PostgreSQL also relies on the operating system's file cache, so giving it much more rarely helps.
  • MySQL innodb_buffer_pool_size: on a dedicated database server this is often 50–75% of RAM. In a 1 GB container, start around 512M; MySQL needs memory beyond the buffer pool for connections and internal tables.
  • Connections: every app instance holds a pool. Add them up: app instances × pool size, plus workers and cron jobs, plus a few for migrations and you, must stay under max_connections.

For example, 3 app containers with a pool of 10 plus 2 workers with a pool of 5 is 40 connections, well under 100. Watch for defaults: node-postgres pools up to 10 per instance, and other ORMs size pools by CPU count. PostgreSQL in particular uses real memory per connection, so raising max_connections into the hundreds is the wrong fix; reduce pool sizes, or put PgBouncer in front.

Keep each database's own memory settings comfortably under its container limit. If the container hits the limit, the kernel kills the database process, which is far worse than a slow query.

Redis: cache, queue or session store?

How you configure Redis depends on whether losing its data is acceptable. A cache can be emptied and rebuilt from the database. A job queue or session store cannot: losing it means lost jobs and logged-out users.

redis.conf (cache only)
maxmemory 256mb
maxmemory-policy allkeys-lru
appendonly no
save ""
redis.conf (queues, sessions)
maxmemory 256mb
maxmemory-policy noeviction
appendonly yes
appendfsync everysec

allkeys-lru evicts the least recently used keys when memory is full, which is exactly what a cache wants. For queues, eviction would silently delete jobs, so use noeviction: writes fail with an error when memory is full, which you will notice. Libraries such as BullMQ expect this. Set maxmemory below the container limit (256 MB under 384 MB above) to leave room for Redis's own overhead and for the copy it forks when saving.

On persistence: RDB snapshots (dump.rdb) are compact point-in-time copies, but you lose everything since the last snapshot. The append-only file (AOF) logs every write; with appendfsync everysec you lose at most about a second of writes on a crash. Use AOF when Redis holds data you can't rebuild. If cache and queues have different needs, run two Redis containers rather than compromising one.

Backups, and a restore you have actually tested

A named volume is not a backup: it is on the same disk as everything else. Take logical dumps on a schedule, copy them off the server, keep a set number of days, and restore one regularly.

PostgreSQL

terminal
mkdir -p backups
# The database, in custom format (compressed, restorable with pg_restore)
docker compose exec -T db sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' \
  > backups/app-$(date +%F).dump
# Roles and passwords, which pg_dump does not include
docker compose exec -T db sh -c 'pg_dumpall -U "$POSTGRES_USER" --globals-only' \
  > backups/globals-$(date +%F).sql
terminal (test restore into a scratch database)
docker compose exec -T db createdb -U postgres restore_test
docker compose exec -T db pg_restore -U postgres -d restore_test --no-owner \
  < backups/app-2026-11-08.dump
docker compose exec -T db psql -U postgres -d restore_test -c '\dt'
docker compose exec -T db dropdb -U postgres restore_test

MySQL

terminal
docker compose exec -T db sh -c \
  'exec mysqldump -uroot -p"$MYSQL_ROOT_PASSWORD" --single-transaction --routines --triggers --events "$MYSQL_DATABASE"' \
  | gzip > backups/app-$(date +%F).sql.gz

--single-transaction gives a consistent dump without locking, but only for InnoDB tables, which is the default engine. MySQL prints a warning about the password on the command line; it stays inside the container. To test a restore:

terminal
docker compose exec -T db sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e "CREATE DATABASE restore_test"'
gunzip -c backups/app-2026-11-08.sql.gz \
  | docker compose exec -T db sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" restore_test'
docker compose exec -T db sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e "SHOW TABLES FROM restore_test"'
docker compose exec -T db sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e "DROP DATABASE restore_test"'

Redis

A cache-only Redis doesn't need backing up. For queues and sessions, trigger a snapshot and copy it out once LASTSAVE has changed:

terminal
docker compose exec -T redis sh -c 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning BGSAVE'
docker compose exec -T redis sh -c 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning LASTSAVE'
docker compose cp redis:/data/dump.rdb backups/redis-$(date +%F).rdb

To restore, stop Redis, copy the file into the volume as dump.rdb, and start it again. With appendonly yes, Redis loads the AOF instead of the RDB on start, so start once with AOF off, then turn it back on with CONFIG SET appendonly yes before restoring the config.

Schedule, copy off, keep a limited history

Put the dump commands in a script run nightly by cron or a systemd timer, then copy the files to another machine or object storage (rsync or rclone), and delete old local files, for example find backups -type f -mtime +14 -delete. A backup that only lives on the server that failed is no help. Test a restore after you first set this up and again every few months; until you have restored one, you have a file, not a backup.

Daily dumps mean you can lose up to a day of data. If that is too much, both databases support point-in-time recovery: continuous WAL archiving in PostgreSQL (tools such as pgBackRest or WAL-G manage it), and binary logs in MySQL, which are on by default in 8.x. That is a larger setup, worth it once the data is valuable enough.

Upgrades and what to watch

Minor versions (17.5 to 17.6, 8.4.5 to 8.4.6, 7.4.1 to 7.4.2) are bug and security fixes. Pinning to postgres:17-alpine or mysql:8.4 means docker compose pull picks them up; take a backup first, then docker compose up -d db.

Don't change postgres:16 to postgres:17 and restart. PostgreSQL's on-disk format changes between major versions and the new version will refuse to start on the old data. A major upgrade means dump and restore into a fresh volume, or pg_upgrade. MySQL can upgrade in place between supported versions (8.0 to 8.4), but not downgrade, and 8.4 disables the old mysql_native_password authentication by default, which can break older clients. Always back up first, and try the upgrade on a copy.

What to check, ideally with alerts rather than by memory:

  • Disk space. A full disk stops a database from writing. Check df -h and docker system df; alert well before 100%.
  • Connections. PostgreSQL: SELECT count(*) FROM pg_stat_activity;. MySQL: SHOW GLOBAL STATUS LIKE 'Threads_connected'; and Max_used_connections. Compare with max_connections.
  • Slow queries. log_min_duration_statement=500 above logs PostgreSQL queries slower than 500 ms to docker compose logs db. MySQL's slow_query_log writes queries over long_query_time seconds to a file in the data directory. Most slow queries are fixed with an index.
  • Redis memory and evictions. INFO memory shows used_memory_human against maxmemory; INFO stats shows evicted_keys. Evictions on a cache are normal; rising fast means it is too small. On a noeviction Redis, watch for write errors in the app.
  • Backups. Check that last night's file exists, is a sensible size, and reached the off-server copy.

Where NevaraCloud fits

If you would rather not run this yourself, an app with a PostgreSQL or MySQL database is our Full-stack plan, and apps that also need Redis, workers or several services run on the Multi-container plan, with services on a private network and persistent volumes backed up. Full-stack starts from LKR 3,500 a month and Multi-container is quoted in LKR (see pricing); the Full-stack plan includes daily backups kept for 7 days. Databases are not exposed to the internet. The fixed-price Starter plan (LKR 1,500 a month) is for frontends only and has no database. More on the container side is on our Docker hosting page.

We don't sell self-managed VPS servers or root access, so if you need full control of the database server, run it yourself with the steps above. If you already run databases on a server elsewhere, in Sri Lanka or abroad, our managed infrastructure service can take over backups, monitoring and patching, quoted after we review the setup.

Rather we handled it?

Managed hosting billed in LKR, DevOps and deployment automation, or hands-on deployment help. Tell us what you're working on.

Discuss your project