Home / Configs / Containers / docker-compose for MySQL

docker-compose for MySQL: example file and generator

Run a local MySQL database in Docker with your own user, password and port, and keep the data between restarts.

For Docker Desktop (Windows, macOS) or Docker Engine with the Compose plugin (Linux).

This docker-compose file starts a MySQL database with one command and keeps your data in a volume. Choose the version, passwords and port below, then run docker compose up -d.

Create your config file

Type your own values. The file below updates as you type, and nothing you type leaves your browser.

Click Generate for a strong one
Click Generate for a strong one
Change it if 3306 is already used

docker-compose.yml
services:
  db:
    image: mysql:8.4
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: change-me-root
      MYSQL_DATABASE: appdb
      MYSQL_USER: app
      MYSQL_PASSWORD: change-me-user
    ports:
      - "3306:3306"
    volumes:
      - mysqldata:/var/lib/mysql
    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h localhost -uroot -p$$MYSQL_ROOT_PASSWORD"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  mysqldata:

How this setup works

Diagram: docker compose up, then MySQL container, then mysqldata volume
docker compose up (one command) → MySQL container (your port) → mysqldata volume (data is kept)

Step-by-step setup

  1. Install Docker Desktop (Windows, macOS) or Docker Engine with the Compose plugin (Linux).
  2. Save the config as docker-compose.yml in an empty folder.
  3. Start it: docker compose up -d. The first start can take up to a minute.
  4. Connect: mysql -h 127.0.0.1 -P 3306 -u app -p appdb.
  5. Read the log if something looks wrong: docker compose logs db.

What the important lines mean

Common errors and how to fix them

Access denied for user
The passwords are only applied the first time. After changing them, reset with docker compose down -v. This deletes the data.
Can’t connect to MySQL server on 127.0.0.1
The container is still starting. Wait a minute and check docker compose logs db.
Bind for 0.0.0.0:3306 failed: port is already allocated
Another MySQL or container uses that port. Pick another port above, such as 3307.
Container shows unhealthy
The root password in the health check does not match. Reset the volume as shown above.

Frequently asked questions

How do I connect to MySQL running in Docker?
Use host 127.0.0.1, the port you chose, and the user and password from the file.
Will I lose my data when I stop the container?
No, as long as the volume stays. Data is lost only if you run docker compose down -v.
Can I use MariaDB instead?
Yes. Change the image to mariadb and keep the same MYSQL_ variables.

Written for: Docker 27, Compose v2, MySQL 8.4 · Updated 2026-10-03

Free tools that help

Fix a problem with this setup

More container configs

See all 41 config generators