Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › database security

How to Run MariaDB in Docker on a Linux VPS

By Freedom251 Team · · 9 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest production pattern is a pinned official MariaDB image, a named volume mounted at /var/lib/mysql, credentials supplied through Docker secrets, and no public port 3306. Docker runs the database process; the volume preserves its files when the container is replaced; your application reaches MariaDB over a private Docker network.

This guide shows a Docker Compose deployment, first-start initialization, application connectivity, backups, upgrades, and the failure modes that most often cause data loss or accidental exposure.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you are building

A VPS deployment has four separate concerns:

  • Image: MariaDB’s official Docker image, with an explicit version tag rather than a moving tag such as latest. The image packaging is maintained in the MariaDB Corporation server-docker repository.
  • Container: The replaceable runtime that starts MariaDB.
  • Persistent storage: A Docker named volume mounted at /var/lib/mysql.
  • Network: A private Docker network shared with the application. Do not publish 3306 to the internet.

Initialization variables are read when the data directory is empty. Once MariaDB has initialized the volume, changing those variables does not rewrite existing users, passwords, or databases. Treat the volume as the database itself and the container as disposable.

Prerequisites and a sensible VPS layout

Host requirements

  • A supported Linux VPS with root or sudo access.
  • Docker Engine and the Docker Compose plugin installed from your distribution’s supported packages.
  • Enough disk space for the database, binary backups, logs, and free space for upgrades. Database size is application-dependent, so set a monitoring threshold rather than relying on a universal minimum.
  • A DNS name and TLS-enabled application if the database serves a public website or API. MariaDB itself should remain private.

Firewall and exposure

At the VPS firewall, allow SSH and only the web ports your application needs. Do not add a public rule for TCP 3306. If a tool on your laptop must administer the database, use an SSH tunnel instead of opening the database port:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
ssh -L 3307:127.0.0.1:3306 admin@your-vps

With the tunnel running, connect your local client to 127.0.0.1:3307. The database still listens only on the VPS loopback interface.

Choose the image tag before you start

The image documentation provides latest and lts moving tags, but tags can point to different releases over time. Production deployments should pin an explicit version tag, preferably a long-term-support line after you have checked that the exact tag is available and compatible with your application. The currently available tag list and LTS number are not fixed here; verify them on Docker Hub immediately before deployment.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not silently change major versions by pulling latest. Record the selected tag in your deployment notes and update it deliberately after a backup and compatibility review.

Create a Compose project with secrets and persistent storage

Directory structure

sudo mkdir -p /opt/mariadb/{secrets,backups}
sudo chown -R $USER:$USER /opt/mariadb
cd /opt/mariadb
umask 077

Create two secret files. Use long, unique random values generated by a password manager or a local cryptographically secure generator. Never copy the example value from an image readme to a public VPS.

printf '%sn' 'replace-with-a-unique-root-password' > secrets/root_password
printf '%sn' 'replace-with-a-different-app-password' > secrets/app_password
chmod 600 secrets/root_password secrets/app_password

The strings above are instructions, not passwords to reuse. Keep the files out of version control; add secrets/ to .gitignore if this directory is part of a repository.

Compose file

Save the following as compose.yaml. It deliberately requires an image tag through the MARIADB_IMAGE_TAG variable, so an accidental unset value cannot select a moving default.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
services:
  mariadb:
    image: mariadb:${MARIADB_IMAGE_TAG:?Set an explicit MariaDB tag in .env}
    restart: unless-stopped
    environment:
      MARIADB_ROOT_PASSWORD_FILE: /run/secrets/mariadb_root_password
      MARIADB_DATABASE: appdb
      MARIADB_USER: appuser
      MARIADB_PASSWORD_FILE: /run/secrets/mariadb_app_password
    secrets:
      - mariadb_root_password
      - mariadb_app_password
    volumes:
      - mariadb_data:/var/lib/mysql
    networks:
      - db_net
    healthcheck:
      test: ['CMD', 'healthcheck.sh', '--connect', '--innodb_initialized']
      interval: 10s
      timeout: 5s
      retries: 10
      start_period: 30s

volumes:
  mariadb_data:

networks:
  db_net:
    internal: true

secrets:
  mariadb_root_password:
    file: ./secrets/root_password
  mariadb_app_password:
    file: ./secrets/app_password

Put the exact tag you selected in a local .env file as MARIADB_IMAGE_TAG=...; do not commit that file if it contains other sensitive settings. The Compose interpolation expression will stop with an error until the variable is set.

The healthcheck.sh command is a commonly used community pattern for the official image. It checks that MariaDB accepts a connection and that InnoDB has completed initialization; it is not an official Compose template.

Why these variables are named MARIADB_*

The image accepts initialization settings such as MARIADB_ROOT_PASSWORD, MARIADB_DATABASE, MARIADB_USER, and MARIADB_PASSWORD. From image tags 10.2.38, 10.3.29, 10.4.19, 10.5.10, and all 10.6 and newer tags, the MARIADB_* names take precedence over their older MYSQL_* equivalents. Prefer the MariaDB names in new files; treat older MYSQL_* examples as legacy. The accepted root credential choices are MARIADB_ROOT_PASSWORD_HASH, MARIADB_ROOT_PASSWORD, MARIADB_ALLOW_EMPTY_ROOT_PASSWORD, or MARIADB_RANDOM_ROOT_PASSWORD, each with a corresponding _FILE form. An empty root password is unsuitable for an internet-facing VPS.

Using _FILE makes the container read the value from a mounted secret instead of placing the password directly in the Compose YAML. The official image documents these options on Docker Hub.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What first initialization creates

On an empty volume, MARIADB_DATABASE: appdb creates the database. The image creates appuser only because both a username and password are supplied, and grants that user privileges on appdb. If either user setting is omitted, no application account is created automatically.

Pull the image and start MariaDB

  1. Change to the project directory and confirm that .env contains the exact tag you intend to run.
  2. Pull that tag explicitly:
    docker compose pull mariadb
  3. Start the service in the background:
    docker compose up -d
  4. Check container state and health:
    docker compose ps
    docker compose logs -f mariadb

    Wait for the health status to become healthy before starting an application that depends on the database.

The first start can take longer while the data directory and system tables are created. A restart with the same volume should not repeat initialization.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Connect an application without publishing 3306

Application in another container

Attach the application service to the same db_net network. Use the Compose service name mariadb as the hostname, port 3306, database appdb, user appuser, and the value stored in secrets/app_password. Docker’s internal DNS resolves the service name; the application does not need a host port mapping.

If the application is defined in a separate Compose project, create a deliberately named external network and attach both projects to it. Do not solve cross-project connectivity by publishing 3306 on every interface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Application running directly on the VPS

If the application is not containerized, publish only to loopback:

ports:
  - '127.0.0.1:3306:3306'

Then configure the application to use host 127.0.0.1 and port 3306. Remove the ports section entirely when every client is on the private Docker network.

Administrative login

Open a root client inside the container so no database port needs to be exposed:

docker compose exec mariadb mariadb -uroot -p

Enter the root password from secrets/root_password when prompted. For routine application work, use appuser; reserve the root account for administration and recovery.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Persistence: what survives and what does not

The named volume mariadb_data is mounted at /var/lib/mysql, the location containing the database files. Removing and recreating the container leaves that volume in place, so the data remains available to the next container using the same mount.

Environment variables are not a password-management system for an already initialized database. Editing .env and running docker compose up -d
a
does not change an existing root or application password. Change credentials explicitly with SQL after checking the actual account host:

docker compose exec mariadb mariadb -uroot -p -e "SELECT User, Host FROM mysql.user;"

Then run an ALTER USER statement for the returned account, using a new secret that is not stored in shell history. Test the new credential before removing the old one or changing application configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Never use docker compose down -v on this project unless you intentionally want to delete the named volume and its data. A normal docker compose down removes containers and the network but leaves the named volume.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Back up MariaDB correctly

Do not back up a live database by copying its raw data directory. Use a logical dump with mariadb-dump (or the compatible mysqldump) or use mariabackup for a physical backup workflow. Store backups outside the VPS as well as locally, protect them with encryption and restricted permissions, and periodically test a restore.

Logical dump example

This command reads the root secret inside the container and writes a SQL dump on the host. Adjust the filename and retention policy to your environment.

docker compose exec -T mariadb sh -c 'mariadb-dump --user=root --password="$(cat /run/secrets/mariadb_root_password)" --all-databases --single-transaction --routines --events' > backups/mariadb-$(date +%F-%H%M).sql
chmod 600 backups/mariadb-*.sql

--single-transaction gives a consistent dump for transactional InnoDB tables without stopping normal reads and writes. Tables using other storage engines may need a different locking strategy; review your schema before relying on this option.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Restore procedure

  1. Choose the target database instance and confirm that the backup file is readable.
  2. For a full restore, stop applications that write to MariaDB so they cannot race the import.
  3. Import through the running container:
    docker compose exec -T mariadb sh -c 'mariadb --user=root --password="$(cat /run/secrets/mariadb_root_password)"' < backups/your-backup.sql
  4. Check the application tables and restart the application. A restore is not proven until the application can read and write expected data.

VPS hardening beyond the container

  • Use the VPS provider’s firewall and the host firewall together where practical; allow SSH only from trusted addresses when possible, plus the web ports required by the application.
  • Keep Docker, the kernel, and MariaDB image tags patched, but review release notes before changing a major database line.
  • Do not expose the Docker socket to the MariaDB container or mount unrelated host directories.
  • Restrict permissions on compose.yaml, .env, and secret files. The secret files should be readable only by the deployment account.
  • Monitor disk usage, container restarts, backup freshness, and MariaDB error logs. Enable slow-query logging and size the InnoDB buffer pool for the workload after measuring memory available on the VPS.

These host-level practices are administration guidance rather than settings supplied by the image documentation; adapt them to your Linux distribution and hosting provider.

Safe upgrades and routine maintenance

  1. Read the release notes for the target MariaDB version and confirm application-driver compatibility.
  2. Run and verify a recent logical or physical backup.
  3. Record the current image tag and volume name.
  4. Change only MARIADB_IMAGE_TAG to the reviewed tag.
  5. Pull and recreate the service:
    docker compose pull mariadb
    docker compose up -d mariadb
  6. Watch health and logs, then run an application smoke test. Keep the old backup until the new version has operated successfully.

Do not assume that setting an image variable will migrate an existing database automatically. The initialization environment is primarily for an empty data directory; upgrades require the image’s documented migration behavior and a tested rollback plan.

Troubleshooting the common failures

The container exits immediately with a password error

Check that exactly one valid root-password method is configured and that the referenced secret file exists inside the project directory. Confirm permissions and inspect docker compose logs mariadb. Do not “fix” the error by enabling an empty root password.

Changing a password in Compose had no effect

The volume is already initialized. Use an explicit SQL ALTER USER operation, update the application secret, and test the new login. Recreating the container alone does not re-run initialization.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The application reports “connection refused”

  • When both services are containers, use hostname mariadb, not localhost; in a container, localhost means that application container.
  • Confirm both services share the same Docker network.
  • Wait for the health check to pass and inspect MariaDB logs.
  • When the application runs on the VPS host, use 127.0.0.1:3306 only if the loopback port mapping is present.

The database appears empty after recreation

Inspect mounts with docker inspect and verify that the new container uses the original mariadb_data volume at /var/lib/mysql. Check that nobody ran docker compose down -v and that the project name did not change, creating a second volume with a similar name.

Port 3306 is visible on the internet

Remove the public port mapping, bind it to 127.0.0.1 if a host process needs it, and close 3306 in the VPS firewall. Use the SSH tunnel described earlier for remote administration.

Backups succeed but cannot be restored

Check the dump file size and exit status, then perform a restore rehearsal on a separate MariaDB instance. Include routines and events when the application uses them, and stop writes during a full restore.

Deployment checklist

  • Official mariadb image selected and an explicit tag recorded.
  • MARIADB_* variables used, with passwords supplied through _FILE secrets.
  • Named volume mounted at /var/lib/mysql.
  • Application database and least-privilege application account created on first initialization.
  • Port 3306 kept on an internal network or bound only to loopback.
  • Health check, restart policy, logs, disk monitoring, and firewall rules verified.
  • Automated dumps or mariabackup jobs stored off the VPS and a restore tested.
  • Upgrade procedure documented, including a fresh backup and rollback point.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

database securityDockerDocker ComposeLinux VPSMariaDBserver administration

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.