Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 111 ยท Language Recipes

Running Databases in Containers

Run PostgreSQL, MySQL and Redis in Docker: persistent volumes, init scripts, credentials, healthchecks, backups with pg_dump and mysqldump, and when not to use containers.

Almost every application needs a database, and running one in a container is the quickest way to get one: docker run, wait a few seconds, connect. No installers, no version conflicts between projects, and a clean slate whenever you want it. The three servers you will meet most often, PostgreSQL, MySQL and Redis, all publish official images with the same conventions.

But a database is the one kind of container that holds state worth keeping. The usual container habit of throwing things away and starting fresh becomes dangerous if the data lives inside the container. This lesson covers what the official images do for you (first-run initialization, init scripts, environment variables), how to persist data with volumes, how to set credentials without leaking them, how to wait for a database to be ready, how to back up and restore, and an honest answer to "should production databases run in Docker at all?" Every command was run against PostgreSQL 17, MySQL 8.4 and Redis 8.

The shape of a database container

All three official images follow one pattern:

TEXT
  image (read-only)            container (writable layer)         volume
 +------------------+         +---------------------------+     +--------------+
 | server binaries  |  run    | server process (PID 1)    |     | data files   |
 | entrypoint script| ------> | env vars -> first-run     | <-> | survive      |
 | default config   |         |   setup, init scripts     |     | docker rm    |
 +------------------+         +---------------------------+     +--------------+

The entrypoint script inspects the data directory when the container starts. If it is empty, the script initializes a new database, creates the user and database named in the environment variables, runs your init scripts, and starts the server. If the directory already holds a database, the script skips all of that and just starts the server. Understanding this one rule explains most of the surprises people hit.

PostgreSQL

First run

CONSOLE
$ docker volume create pgdata
pgdata
$ docker run -d --name pg \
    -e POSTGRES_USER=app \
    -e POSTGRES_PASSWORD=s3cret-demo \
    -e POSTGRES_DB=appdb \
    -v pgdata:/var/lib/postgresql/data \
    -v "$PWD/db/init:/docker-entrypoint-initdb.d:ro" \
    -p 127.0.0.1:5432:5432 \
    postgres:17-alpine

What each option does:

  • POSTGRES_PASSWORD is the only required variable. POSTGRES_USER (default postgres) and POSTGRES_DB (default: the user name) choose the first superuser and database.
  • -v pgdata:/var/lib/postgresql/data mounts a named volume on PostgreSQL's data directory. This is what keeps your data (see Volumes). The image declares this path as a volume, so without your -v Docker would still create an anonymous volume there, which is easy to lose track of.
  • -v ...:/docker-entrypoint-initdb.d:ro mounts a folder of init scripts, read-only.
  • -p 127.0.0.1:5432:5432 publishes the port on the loopback interface only. A database on 0.0.0.0 is reachable by every machine that can reach yours (see Publishing Ports). If only other containers need the database, publish nothing at all and let them connect over a Docker network.

The init folder holds 01-schema.sql:

SQL
CREATE TABLE notes (
  id SERIAL PRIMARY KEY,
  body TEXT NOT NULL
);
INSERT INTO notes (body) VALUES ('created by an init script');

The container log shows the initialization in order:

CONSOLE
$ docker logs pg 2>&1 | grep -E "running|CREATE|INSERT|complete"
The database cluster will be initialized with locale "en_US.utf8".
running bootstrap script ... ok
CREATE DATABASE
/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/01-schema.sql
CREATE TABLE
INSERT 0 1
PostgreSQL init process complete; ready for start up.

Scripts in docker-entrypoint-initdb.d run in alphabetical order, which is why they are prefixed with numbers. The image runs *.sql, *.sql.gz and *.sh files. Query the result with the psql client that ships inside the image:

CONSOLE
$ docker exec pg psql -U app -d appdb -c "SELECT * FROM notes;"
 id |           body            
----+---------------------------
  1 | created by an init script
(1 row)

$ docker exec pg pg_isready -U app -d appdb
/var/run/postgresql:5432 - accepting connections

pg_isready is the tool to remember for health checks.

The init-once rule

Add a second row, delete the container, and start a new one on the same volume, this time with a different POSTGRES_PASSWORD:

CONSOLE
$ docker exec pg psql -U app -d appdb -c "INSERT INTO notes (body) VALUES ('added later');"
INSERT 0 1
$ docker rm -f pg
$ docker run -d --name pg -e POSTGRES_USER=app -e POSTGRES_PASSWORD=other \
    -e POSTGRES_DB=appdb -v pgdata:/var/lib/postgresql/data \
    -v "$PWD/db/init:/docker-entrypoint-initdb.d:ro" postgres:17-alpine
$ docker logs pg 2>&1 | head -4

PostgreSQL Database directory appears to contain a database; Skipping initialization

2026-10-23 15:44:59.944 UTC [1] LOG:  starting PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
$ docker exec pg psql -U app -d appdb -c "SELECT * FROM notes;"
 id |           body            
----+---------------------------
  1 | created by an init script
  2 | added later
(2 rows)

The data survived, the init script did not run again (it would have failed on CREATE TABLE), and the new password was ignored. A client connecting over the network with the password other is rejected, and the original still works:

CONSOLE
$ docker run --rm --network mynet -e PGPASSWORD=other postgres:17-alpine \
    psql -h pg -U app -d appdb -tc "select 'connected'"
psql: error: connection to server at "pg" (172.21.0.2), port 5432 failed: FATAL:  password authentication failed for user "app"
$ docker run --rm --network mynet -e PGPASSWORD=s3cret-demo postgres:17-alpine \
    psql -h pg -U app -d appdb -tc "select 'connected'"
 connected

The environment variables only matter on the first start. Changing POSTGRES_PASSWORD, POSTGRES_USER or MYSQL_ROOT_PASSWORD in your Compose file later does nothing to an existing volume; the password is stored inside the database. Change it with SQL (ALTER USER app PASSWORD '...'), or, in development, delete the volume and start over. The same goes for init scripts: editing them has no effect once the data directory exists. (That is also why the password test above ran from a second container: inside the PostgreSQL container, local connections are trusted without a password.)

The mount point is version dependent. PostgreSQL 17 images keep data in /var/lib/postgresql/data, but the path can differ in other major versions of the image. Always read the image page for the exact tag you use, and never mount a volume of an old major version onto a new major version: PostgreSQL needs a dump/restore or pg_upgrade between majors.

MySQL

MySQL's image works the same way with different variable names. The root password is mandatory (or a documented alternative such as MYSQL_ALLOW_EMPTY_PASSWORD):

CONSOLE
$ docker run -d --name my \
    -e MYSQL_ROOT_PASSWORD=root-demo \
    -e MYSQL_DATABASE=appdb \
    -e MYSQL_USER=app \
    -e MYSQL_PASSWORD=app-demo \
    -v mydata:/var/lib/mysql \
    -v "$PWD/db/mysql-init:/docker-entrypoint-initdb.d:ro" \
    mysql:8.4

MYSQL_DATABASE, MYSQL_USER and MYSQL_PASSWORD create an application user with full rights on that one database, so your app never needs root. The log shows the temporary-server dance that MySQL's entrypoint performs:

CONSOLE
$ docker logs my 2>&1 | grep -E "Entrypoint|ready for connections" | head
[Entrypoint]: Entrypoint script for MySQL Server 8.4.13-1.el9 started.
[Entrypoint]: Initializing database files
[Entrypoint]: Database files initialized
[Entrypoint]: Starting temporary server
[Entrypoint]: /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/01-schema.sql

During initialization MySQL runs a temporary server that listens on a socket only (not on the network), runs your scripts, shuts down, and then the real server starts. That is why a TCP health check passes only when the real server is up. Use the same TCP-based check that your application will use:

CONSOLE
$ docker run -d --name my ... \
    --health-cmd 'mysqladmin ping -h 127.0.0.1 -uroot -proot-demo --silent' \
    --health-interval 3s mysql:8.4
$ docker inspect -f '{{.State.Health.Status}}' my
healthy
$ docker exec my mysql -uapp -papp-demo appdb -e "SELECT * FROM notes"
id	body
1	created by an init script

(MySQL warns "Using a password on the command line interface can be insecure"; the warning goes to stderr and is omitted above.) The same init-once rule holds. We removed the container and started a new one on the volume with MYSQL_ROOT_PASSWORD=changed:

CONSOLE
$ docker exec my2 mysql -uroot -pchanged -e "select 1"
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
$ docker exec my2 mysql -uroot -proot-demo appdb -e "select count(*) from notes"
count(*)
2

The old root password remains, and the rows added earlier are all there. Also note that the MySQL image is large (1.12 GB in our pull), so the first docker pull takes a while.

Redis

Redis needs no setup at all, and by default it is an in-memory cache. The official image sets /data as the working directory, which is where Redis writes its snapshots and logs.

CONSOLE
$ docker run --rm redis:alpine redis-server --version
Redis server v=8.10.2 sha=00000000:1 malloc=jemalloc-5.3.0 bits=64 build=8d909ac7aa12fd40
$ docker run -d --name rd redis:alpine
$ docker exec rd redis-cli config get appendonly
appendonly
no
$ docker exec rd redis-cli config get save
save
3600 1 300 100 60 10000

By default Redis takes RDB snapshots (the save rules: after 3,600 s if one key changed, after 300 s if 100 changed, after 60 s if 10,000 changed) and keeps the append-only log off. If Redis is only a cache, that is fine: lose it and the app refills it. If it holds data you cannot recompute (queues, sessions), turn on the append-only file and mount a volume at /data. Options go after the image name, because the entrypoint passes them on to redis-server:

CONSOLE
$ docker run -d --name rd -v redisdata:/data --network mynet \
    redis:alpine redis-server --appendonly yes --requirepass redis-demo
$ docker exec rd redis-cli ping
NOAUTH Authentication required.
$ docker exec rd redis-cli -a redis-demo --no-auth-warning set greeting hello
OK
$ docker exec rd ls -R /data
/data:
appendonlydir

/data/appendonlydir:
appendonly.aof.1.base.rdb
appendonly.aof.1.incr.aof
appendonly.aof.manifest

After removing the container and starting a new one on the same volume and flags, the key is still there:

CONSOLE
$ docker exec rd redis-cli -a redis-demo --no-auth-warning get greeting
hello
$ docker exec rd redis-cli -a redis-demo --no-auth-warning info persistence | grep aof_enabled
aof_enabled:1

--requirepass sets a password; without it any container on the same network can read and write your data. Never publish Redis' port to the world: unauthenticated Redis on the internet is a classic way to get hacked. Keep it on the internal Docker network.

Credentials without leaking them

Environment variables are convenient but visible: docker inspect shows them, and anyone who can reach the daemon sees them. Better options, in order:

  1. Do not put the password in the Compose file. Reference a variable and keep the real value in an untracked .env file or the shell: POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}. The :? form makes Compose stop with a clear error if it is missing.
  2. Use *_FILE variables and Docker secrets. The PostgreSQL and MySQL images read POSTGRES_PASSWORD_FILE / MYSQL_ROOT_PASSWORD_FILE and load the secret from a file instead:
YAML
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_DB: appdb
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
secrets:
  db_password:
    file: ./db_password.txt

We ran this file; env inside the container shows only the path, ls /run/secrets lists db_password, and a connection with the file's contents succeeded while a wrong password failed. Full treatment in Managing Secrets and Environment, Variables and Secrets.

Never use the sample passwords from tutorials, including this one, outside a throwaway demo.

A complete Compose file with health ordering

Here is a stack with PostgreSQL, Redis and a client that must wait until both are healthy. We built and ran exactly this file:

YAML
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_DB: appdb
      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 3s
      timeout: 3s
      retries: 10
    restart: unless-stopped
    ports:
      - "127.0.0.1:5432:5432"

  cache:
    image: redis:alpine
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 3s
    restart: unless-stopped

  app:
    image: postgres:17-alpine
    environment:
      PGPASSWORD: ${DB_PASSWORD}
    command: ["psql", "-h", "db", "-U", "app", "-d", "appdb", "-c", "select 'app reached the database' as result"]
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy

volumes:
  pgdata:
  redisdata:

(app here is just a psql one-liner standing in for your real application.) With DB_PASSWORD=compose-demo-pw in a .env file:

CONSOLE
$ docker compose up -d
 Container db-1 Started
 Container cache-1 Started
 Container cache-1 Waiting
 Container db-1 Waiting
 Container cache-1 Healthy
 Container db-1 Healthy
 Container app-1 Started
$ docker compose logs app
app-1  |          result          
app-1  | --------------------------
app-1  |  app reached the database
app-1  | (1 row)
$ docker compose ps -a --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
SERVICE   STATUS                     PORTS
app       Exited (0) 2 seconds ago   
cache     Up 9 seconds (healthy)     6379/tcp
db        Up 11 seconds (healthy)    127.0.0.1:5432->5432/tcp

depends_on with condition: service_healthy is what makes app wait; plain depends_on only waits for the container to start, long before the database accepts connections. Without DB_PASSWORD, Compose refuses to start and prints our error message. See Startup Order and Health.

Next, prove the data outlives the containers. We inserted a row in PostgreSQL and a key in Redis, then removed everything with docker compose down (containers and network, not volumes) and started again:

CONSOLE
$ docker compose exec db psql -U app -d appdb -c "create table visits (n int); insert into visits values (1);"
CREATE TABLE
INSERT 0 1
$ docker compose exec cache redis-cli set counter 42
OK
$ docker compose down
$ docker compose up -d
$ docker compose exec db psql -U app -d appdb -tc "select count(*) from visits"
     1
$ docker compose exec cache redis-cli get counter
42

docker compose down -v deletes the named volumes, and with them all the database data. We used it deliberately to clean up. Never put -v in a script that points at data you care about.

Backups and restores

A volume is not a backup: it dies with the disk, with a mistaken down -v, or with a corrupted write. Take logical dumps with the tools inside the image.

CONSOLE
$ docker compose exec -T db pg_dump -U app appdb > backup.sql
$ grep "CREATE TABLE" backup.sql
CREATE TABLE public.visits (

Restore into a fresh database the same way, with the input redirected into psql:

CONSOLE
$ docker exec pg createdb -U app copy1
$ docker exec -i pg psql -U app -d copy1 -q < dump.sql
$ docker exec pg psql -U app -d copy1 -tc "select count(*) from notes"
     2

Use -T (no pseudo-terminal) for docker compose exec and -i for docker exec when you pipe data in or out, or the stream gets corrupted by terminal handling. For large databases pg_dump -Fc writes a compressed custom format restored with pg_restore. MySQL's equivalent is mysqldump:

CONSOLE
$ docker exec my sh -c 'mysqldump -uroot -proot-demo --no-tablespaces appdb 2>/dev/null' | grep -E "CREATE TABLE|INSERT INTO"
CREATE TABLE `notes` (
INSERT INTO `notes` VALUES (1,'created by an init script'),(2,'added later');

For Redis, redis-cli bgsave writes an RDB snapshot into the data directory and you copy /data out. More methods, including archiving a volume with a helper container, are in Backup and Restore. Schedule dumps, store them off the host, and test a restore. An untested backup is a hope.

So, should production databases run in containers?

It depends on who looks after them.

Containers are great for: development and CI (a throwaway database per test run), integration tests, demos, and small single-host deployments where the volume lives on a backed-up disk.

Think twice for production when:

  • You do not have a tested backup and restore routine, or nobody knows how to recover a crashed volume.
  • You need high availability, automated failover or point-in-time recovery. Doing that with containers means building a lot yourself (or using an operator on Kubernetes). A managed database from your cloud provider does it for you.
  • You need the last drop of I/O performance or fine control over the kernel and storage. Container overhead for a database is small, but a network filesystem or the wrong storage driver under a volume can be a bottleneck. See Volume Drivers and Remote Storage.
  • You run a single Docker host and treat it as a pet: the whole database goes down whenever that host reboots.

Many teams use containers for databases in development and managed services in production, with identical SQL dialect and major version. That combination gives you the convenience without the operational risk.

Pitfalls checklist

  • Forgetting the volume, or mounting it at the wrong path, so data vanishes with the container.
  • Expecting changed environment variables or edited init scripts to apply to existing data.
  • Publishing the database port on all interfaces (-p 5432:5432).
  • Starting the app before the database is ready (use health checks).
  • Upgrading the image tag (postgres:latest) onto an old data directory. Pin the major version.
  • Giving a database container no memory limit and no restart policy. Add restart: unless-stopped and set a sensible limit (see Resource Limits).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You change POSTGRES_PASSWORD in your Compose file and run docker compose up -d again. The database already has a named volume. What happens to the password?

    The entrypoint script initializes a database only when the data directory is empty. With existing data it skips initialization, so the new password is ignored. We saw the original password still work and the new one rejected.
  2. 2. What does a file in /docker-entrypoint-initdb.d do?

    The *.sql, *.sql.gz and *.sh files are executed in alphabetical order on first initialization only. On the second start our log said that the directory already contained a database and initialization was skipped.
  3. 3. Why use depends_on with condition: service_healthy for an application and its database?

    A started container is not necessarily a ready database. With a healthcheck (pg_isready) and service_healthy, Compose starts the app only after the database reports healthy.
  4. 4. Which command deletes the database volumes of a Compose project?

    down removes containers and networks but keeps named volumes. Adding -v removes the volumes, which destroys the data.
  5. 5. Why is Redis started with --appendonly yes and a volume on /data in this lesson?

    By default appendonly is no and Redis relies on RDB snapshot rules. The append-only file in /data/appendonlydir records writes, and a new container on the same volume still returned the key.

Summary

  • Official database images initialize on first start only: env vars and init scripts apply when the data directory is empty, then are ignored.
  • Persist data with a named volume on the right path (/var/lib/postgresql/data, /var/lib/mysql, /data for Redis), and keep ports on 127.0.0.1 or on an internal network.
  • Put init SQL or shell scripts in /docker-entrypoint-initdb.d; they run in alphabetical order.
  • Do not hard-code passwords: use ${VAR:?} with a .env file, or *_FILE variables with Docker secrets.
  • Use pg_isready, mysqladmin ping or redis-cli ping in health checks and depends_on: condition: service_healthy so apps wait for the database.
  • Back up with pg_dump / mysqldump (use -T or -i when piping), store copies elsewhere, and test restores. down -v deletes the data.
  • Redis defaults to snapshots only; enable --appendonly yes and --requirepass when it holds data that matters.
  • Containers suit development, tests and small deployments; for serious production needs consider managed databases.

Next: Nginx and Reverse Proxies