Chrooting MySQL on Debian

It’s quite easy to chroot bind9 and apache on Debian. (See this page for bind9 and libapache2-mod-chroot or libapache2-mod-security for apache.)

But I’ve found no guide for chrooting MySQL, so here’s my short recipe:

  • Prepare the chroot directory. It’s recommended to use an extra partition/filesystem for it. I will use /srv/mysql (which is an LVM2 partition with an ext3 filesystem on my system) for the rest of the text.
  • Stop MySQL:
    /etc/init.d/mysql stop
  • Copy the databases to new location:
    mkdir -p /srv/mysql/var/lib
    cp -a /var/lib/mysql /srv/mysql/var/lib
  • Copy this script to /etc/default/mysql-chroot
  • Edit /etc/init.d/mysql:
    • Source the mysql-chroot script somewhere at the top:

      test -x /usr/sbin/mysqld || exit 0

      . /etc/default/mysql-chroot

      SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)

    • Run setup_chroot right in the start section:

      if mysqld_status check_alive nowarn; then
      echo "...already running."
      else
      setup_chroot
      /usr/bin/mysqld_safe > /dev/null 2>&1 &
    • Somehow /var/run/mysqld/mysqld.pid disappears after each start. We have to create it each time, otherwise the stop command won’t work properly:

      if mysqld_status check_alive warn; then
      echo "."
      ln -sf $CHROOT_DIR/var/run/mysqld/mysqld.pid \
      /var/run/mysqld

      # Now start mysqlcheck or whatever the admin wants.
      /etc/mysql/debian-start
  • In /etc/mysql/debian.cnf, change the socket line to:
    socket = /srv/mysql/var/run/mysqld/mysqld.sock
  • In /etc/mysql/my.cnf:
    • Change the socket line in the [client] section to:
      socket = /srv/mysql/var/run/mysqld/mysqld.sock

      Don’t change the socket lines in the other sections!

    • Add
      chroot = /srv/mysql

      to the [mysqld] section.

  • Prepend /srv/mysql to the log files listed in /etc/logrotate.d/mysql-server
  • Start MySQL:
    /etc/init.d/mysql start
  • Check /var/log/syslog for errors ;-)

March 13th, 2005: I’ve updated the script for newer Debian packages, see Updated MySQL Chroot Script for more information.

July 30th, 2006: These modifications still work fine on the current stable Debian release (3.1, “sarge”). The mysql packages in the testing (”etch”) and unstable (”sid”) distributions of Debian need a few additional changes, I’ll post an updated guide in a few days.

December 30th, 2006: I’ve made an updated guide on how to chroot more recent MySQL packages on Debian and Ubuntu

None
A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".