Black FridayDB Pro for $19.99 $99Ends in0d00h00m00s
Back to Blog

MySQL Docker Compose: a working setup with healthchecks and init scripts

JayJay

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

mysql-compose/
├── compose.yaml
├── .env
├── init/
│   ├── 01-schema.sql
│   └── 02-seed.sql
└── app/
    ├── Dockerfile
    ├── package.json
    └── index.js

Step 1: the MySQL Docker Compose file

YAML
services:
  db:
    image: mysql:8.4
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?set MYSQL_ROOT_PASSWORD in .env}
      MYSQL_DATABASE: shop
      MYSQL_USER: shop
      MYSQL_PASSWORD: ${MYSQL_PASSWORD:?set MYSQL_PASSWORD in .env}
    ports:
      - "127.0.0.1:3306:3306"
    volumes:
      - mysql-data:/var/lib/mysql
      - ./init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "--silent"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 30s

  app:
    build: ./app
    environment:
      DB_HOST: db
      DB_PORT: 3306
      DB_USER: shop
      DB_PASSWORD: ${MYSQL_PASSWORD}
      DB_NAME: shop
    depends_on:
      db:
        condition: service_healthy

volumes:
  mysql-data:

And a .env file next to it. Compose reads it automatically:

MYSQL_ROOT_PASSWORD=change-me-root
MYSQL_PASSWORD=change-me-app

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:

error while interpolating services.db.environment.MYSQL_ROOT_PASSWORD: required variable MYSQL_ROOT_PASSWORD is missing a value: set MYSQL_ROOT_PASSWORD in .env

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:

VariableWhat it does
MYSQL_ROOT_PASSWORDSets the root password. One of this, MYSQL_ALLOW_EMPTY_PASSWORD, or MYSQL_RANDOM_ROOT_PASSWORD is required
MYSQL_DATABASECreates a database with this name
MYSQL_USER, MYSQL_PASSWORDCreates a user with ALL privileges on MYSQL_DATABASE. Both must be set
MYSQL_ROOT_HOSTHost part for the root account. Defaults to %, so root can log in from any host
MYSQL_RANDOM_ROOT_PASSWORDGenerates 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:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

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:

SQL
CREATE TABLE products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  price DECIMAL(8,2) NOT NULL
);

init/02-seed.sql:

SQL
INSERT INTO products (name, price) VALUES
  ('Keyboard', 49.00),
  ('Mouse', 19.00),
  ('Monitor', 189.00);

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:

[Note] [Entrypoint]: /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/01-schema.sql
[Note] [Entrypoint]: /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/02-seed.sql
[Note] [Entrypoint]: MySQL init process done. Ready for start up.

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:

/usr/sbin/mysqld: ready for connections. Version: '8.4.11'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.

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:

YAML
test: ["CMD", "mysqladmin", "ping", "--silent"]

The app crashed:

Error: connect ECONNREFUSED 172.19.0.2:3306

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):

app-1  | [
app-1  |   { id: 1, name: 'Keyboard', price: '49.00' },
app-1  |   { id: 2, name: 'Mouse', price: '19.00' },
app-1  |   { id: 3, name: 'Monitor', price: '189.00' },
app-1  |   { id: 4, name: 'Desk Mat', price: '15.00' }
app-1  | ]
app-1 exited with code 0

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:

mysqladmin: connect to server at '127.0.0.1' failed
error: 'Access denied for user 'root'@'127.0.0.1' (using password: NO)'

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.

DB Pro

Work With Your Databases Like A Pro

Query, explore, and manage your databases with a beautiful desktop app and built-in AI.

Download Now
DB Pro Dashboard

Step 5: connecting from an app container

The app is a small Node.js script using mysql2. app/package.json:

JSON
{
  "name": "shop-app",
  "private": true,
  "type": "module",
  "dependencies": {
    "mysql2": "^3.11.0"
  }
}

app/index.js:

JS
import mysql from 'mysql2/promise';

const conn = await mysql.createConnection({
  host: process.env.DB_HOST,
  port: Number(process.env.DB_PORT),
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
});

const [rows] = await conn.query('SELECT id, name, price FROM products');
console.log(rows);
await conn.end();

app/Dockerfile:

DOCKERFILE
FROM node:22-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY index.js .
CMD ["node", "index.js"]

Start everything:

BASH
docker compose up -d --build

Compose starts db, prints Waiting until the healthcheck reports Healthy, and only then starts app. The app's output:

BASH
docker compose logs app
app-1  | [
app-1  |   { id: 1, name: 'Keyboard', price: '49.00' },
app-1  |   { id: 2, name: 'Mouse', price: '19.00' },
app-1  |   { id: 3, name: 'Monitor', price: '189.00' }
app-1  | ]

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:

AggregateError:
    Error: connect ECONNREFUSED ::1:3306
    Error: connect ECONNREFUSED 127.0.0.1:3306

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:

BASH
docker compose exec db mysql -u shop -p shop

Port 3306 already in use

If MySQL is already installed on your machine, or another container has the port, up fails with:

Bind for 127.0.0.1:3306 failed: port is already allocated

Map a different host port, and connect to that one from the host:

YAML
ports:
  - "127.0.0.1:3307:3306"

The app container is unaffected. It still connects to db:3306.

Step 7: stopping, keeping data, and resetting

BASH
# Stop and remove containers, keep the data volume
docker compose down

# Stop and delete the data volume too
docker compose down -v

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