MySQL Docker Compose: a working setup with healthchecks and init scripts
This post builds a MySQL Docker Compose setup you can copy: a MySQL 8.4 container with a persistent volume, seed data loaded on first start, a healthcheck, and a Node.js app container that waits for the database before it connects. Every file here was run with docker compose up, and the output below is copied from those runs.
The easy healthcheck to write for MySQL has a bug: it reports the database as ready while the init scripts are still running, so the app starts, connects, and gets ECONNREFUSED. The fix is one flag, covered in step 4.
Prerequisites: Docker with the Compose plugin (docker compose version should print v2.x). Everything below was tested with Docker Compose v2.37 and the mysql:8.4 image, which shipped MySQL 8.4.11.
The project layout
Step 1: the MySQL Docker Compose file
And a .env file next to it. Compose reads it automatically:
Keep .env out of version control. The :? syntax makes Compose refuse to start if a variable is missing, instead of creating a database you cannot log in to. With no .env file:
There is no version: key at the top. Compose v2 ignores it, and adding one prints a warning that "the attribute version is obsolete, it will be ignored".
Pin the image tag
The file uses mysql:8.4, not mysql:latest. On Docker Hub today, latest and innovation point at the 26.x Innovation releases, and lts points at 9.7. 8.4 stays on the 8.4 LTS series and only moves between patch releases.
Innovation releases add and remove features between versions. The MySQL manual only supports in-place downgrades within an LTS series, so once a newer server has upgraded your data directory, going back means a dump and reload. If latest moves while you are not paying attention, your volume gets upgraded on the next pull. Pick a version on purpose.
Step 2: environment variables
The official image reads these on first start:
| Variable | What it does |
|---|---|
MYSQL_ROOT_PASSWORD | Sets the root password. One of this, MYSQL_ALLOW_EMPTY_PASSWORD, or MYSQL_RANDOM_ROOT_PASSWORD is required |
MYSQL_DATABASE | Creates a database with this name |
MYSQL_USER, MYSQL_PASSWORD | Creates a user with ALL privileges on MYSQL_DATABASE. Both must be set |
MYSQL_ROOT_HOST | Host part for the root account. Defaults to %, so root can log in from any host |
MYSQL_RANDOM_ROOT_PASSWORD | Generates a root password and prints it in the logs as GENERATED ROOT PASSWORD: |
Each also has a _FILE variant (for example MYSQL_ROOT_PASSWORD_FILE) that reads the value from a file, which is how you use Docker secrets.
Setting MYSQL_USER: root is an error. The entrypoint exits and tells you to use the root password variables instead.
Your app should connect as the shop user, not root. It has full rights on the shop database and none on anything else.
These variables only work once
The entrypoint reads them only when the data directory is empty. After the first start, changing them does nothing. I changed MYSQL_ROOT_PASSWORD in .env, ran docker compose down and docker compose up -d (which keeps the volume), and tried the new password:
The old password still worked. To change a password on an existing database, use ALTER USER in SQL. To start over from scratch, delete the volume (see step 6).
Step 3: init scripts
Anything in /docker-entrypoint-initdb.d runs on first start, in alphabetical order. That is why the file names are numbered. .sql, .sql.gz, .sql.bz2, .sql.xz, .sql.zst, and .sh files are all picked up.
init/01-schema.sql:
init/02-seed.sql:
Neither file has a USE shop; line. When MYSQL_DATABASE is set, the entrypoint runs .sql files against that database. The container logs show them running:
A mysqldump file works here too. Drop backup.sql.gz into init/ and a fresh container starts with that data. Our mysqldump guide covers producing one.
Init scripts only run on an empty volume
The same once-only rule applies. After the first start, I added 03-more.sql with another INSERT, then ran docker compose down and docker compose up -d. The logs showed no running /docker-entrypoint-initdb.d/... lines, and the table still had 3 rows. There is no error or warning when a script is skipped.
Init scripts are for bootstrapping a new database. For schema changes on an existing one, use a migration tool.
Step 4: a healthcheck that waits for the real server
The official MySQL image has no healthcheck of its own, so depends_on with condition: service_healthy does nothing until you define one.
The obvious healthcheck is mysqladmin ping. Without -h, it connects through the Unix socket inside the container, and that is where the problem is.
On first start, the entrypoint runs a temporary MySQL server to create users and run your init scripts. That server listens on the socket but has networking turned off. The log line gives it away with port: 0:
A socket ping succeeds against this temporary server. Docker marks the container healthy, Compose starts your app, and the app connects over TCP to a port nothing is listening on yet.
To reproduce it, I added an init script that sleeps for 25 seconds (SELECT SLEEP(25);) to stand in for a slow seed load, and used a healthcheck without -h:
The app crashed:
With -h 127.0.0.1, mysqladmin uses TCP, which fails until the real server starts after init finishes. Same slow init script, TCP healthcheck (the fourth row comes from the 03-more.sql file added in step 3, which ran this time because the volume was new):
The healthcheck does not need a password
The healthcheck passes no username or password, and it still works. mysqladmin ping exits with status 0 whenever the server answers, even if the answer is an authentication failure:
The exit code for that was 0. The MySQL manual documents this: an access-denied reply still means the server is running. So the healthcheck needs no credentials, and with --silent it prints nothing at all.
start_period: 30s gives first-time initialization room. Failed checks during the start period do not count against retries.
Work With Your Databases Like A Pro
Query, explore, and manage your databases with a beautiful desktop app and built-in AI.
Download Now
Step 5: connecting from an app container
The app is a small Node.js script using mysql2. app/package.json:
app/index.js:
app/Dockerfile:
Start everything:
Compose starts db, prints Waiting until the healthcheck reports Healthy, and only then starts app. The app's output:
price comes back as the string '49.00', not a number. mysql2 returns DECIMAL columns as strings so no precision is lost. Convert them yourself where you need arithmetic.
Use the service name, not localhost
Inside the app container, the database host is db, the service name. Compose puts both services on a shared network where each service name resolves to its container.
localhost inside the app container is the app container itself. Setting DB_HOST=localhost gives:
The same goes for the port. Containers on the Compose network talk on MySQL's own port, 3306, whatever you map in ports:. The ports: mapping only matters for connections from outside Docker.
Step 6: connecting from your machine
The ports: entry publishes MySQL on your machine's port 3306. Binding it to 127.0.0.1 means only your machine can reach it. With a bare "3306:3306", Docker listens on every network interface, so anyone on your network can reach the database.
From the host, use 127.0.0.1 rather than localhost. The mysql command-line client treats localhost as "use the Unix socket", and there is no MySQL socket on your machine, so you get error 2002, Can't connect to local MySQL server through socket, followed by whatever socket path your client defaults to.
The same Node.js script, run on the host with DB_HOST=127.0.0.1, returns the same three rows. A GUI client works with the same settings: host 127.0.0.1, port 3306, user shop, and the password from .env. DB Pro's MySQL client connects to it like any other MySQL server.
For a quick shell without installing anything, use the client inside the container:
Port 3306 already in use
If MySQL is already installed on your machine, or another container has the port, up fails with:
Map a different host port, and connect to that one from the host:
The app container is unaffected. It still connects to db:3306.
Step 7: stopping, keeping data, and resetting
The named volume mysql-data survives down, so your data is still there on the next up. down -v deletes it. On the next start, the environment variables and init scripts all run again against an empty directory. That is the reset button when you change the seed data, and the way to lose everything if you run it by mistake.
Troubleshooting
The app gets ECONNREFUSED on startup even with depends_on. Check that the healthcheck uses -h 127.0.0.1. A socket ping reports healthy during initialization.
A changed password or database name has no effect. The environment variables only apply to an empty volume. Change it in SQL, or docker compose down -v if the data is disposable.
A new init script did not run. Same cause. Init scripts run once, on an empty volume, and a skipped script produces no error.
Access denied for user 'shop'@'172.19.0.1' from the host. The password is wrong, or it was changed in .env after the volume was created. The IP in that message is the Compose network's gateway address, which is how connections from the host appeared to MySQL in this setup.
Is this setup fine for production?
It is built for local development and CI: matching your production MySQL version in a container you can throw away and rebuild in seconds.
Production needs more than a Compose file. The data needs durable storage and tested backups, and upgrades need a plan. None of that is specific to Docker. If what you want is to avoid running MySQL yourself, a managed service handles those parts.
For the same setup with PostgreSQL, including its own version of the socket healthcheck problem, see Postgres Docker: the complete 2026 guide. Once your data is in, how to fix slow MySQL queries is the next step.
Keep Reading
MySQL Alternatives: 9 Databases Worth Considering in 2026
The best MySQL alternatives compared: MariaDB, Percona Server, PostgreSQL, PlanetScale, Vitess, TiDB, Aurora MySQL, SQL Server, and SQLite, with compatibility notes tested in Docker.
MySQL vs SQL Server: Cost, Syntax, and Behaviour Compared
MySQL vs SQL Server (MSSQL) compared with real output from MySQL 8.4 and SQL Server 2025: licensing, T-SQL differences, locking, collations, high availability, tooling, and when to pick each.
PostgreSQL vs MySQL: Real Differences, Tested Side by Side
PostgreSQL vs MySQL compared with real output from PostgreSQL 18 and MySQL 8.4: schema changes, type strictness, collations, upserts, JSON, concurrency, licensing, and when to choose each.