Docker: create a MySQL container

In tutorial we will create a MySQL Docker image from a base Ubuntu image. We will do the following to create our MySQL container:

  • Create a Dockerfile with commands to install and configure MySQL server
  • Create a shell script for creating a user, database and starting the server
  • Build an image named mysql from the created files
  • Create a container from the mysql image
# Create a directory name mysql and cd in to the same
mkdir mysql && cd mysql
# Create a file named and copy the following shell script on to the file:
# This script starts the database server.
echo "Creating user $user for databases loaded from $url"
# Now the provided user credentials are added
/usr/sbin/mysqld &
sleep 5
echo "Creating user"
echo "CREATE USER '$user' IDENTIFIED BY '$password'" | mysql --default-character-set=utf8
echo "REVOKE ALL PRIVILEGES ON *.* FROM '$user'@'%'; FLUSH PRIVILEGES" | mysql --default-character-set=utf8
echo "GRANT SELECT ON *.* TO '$user'@'%'; FLUSH PRIVILEGES" | mysql --default-character-set=utf8
echo "finished"
echo "CREATE DATABASE wordpress" | mysql --default-character-set=utf8
if [ "$right" = "WRITE" ]; then
echo "adding write access"
echo "GRANT ALL PRIVILEGES ON *.* TO '$user'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES" | mysql --default-character-set=utf8
# And we restart the server to go operational
mysqladmin shutdown
echo "Starting MySQL Server"
# Create a Dockerfile and copy the following snippet on to the file:
FROM ubuntu:latest
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get -y install mysql-client mysql-server curl
# Changes the bind address to on my.cnf file to get remote access
RUN sed -i -e"s/^bind-address\s*=\s* =" /etc/mysql/my.cnf
ENV user Docker
ENV password root
ENV access WRITE
ADD ./ /usr/local/bin/
RUN chmod +x /usr/local/bin/
ENTRYPOINT /usr/sbin/mysqld
# Run the following Docker build command to build our mysql image
docker build -t mysql .
# You can start a mysql container using the following Docker command
docker run -d -p 3306:3306 --name db mysql