I have a Dockerfile to install MySQL server in a container, which I then start like this:
sudo docker run -t -i 09d18b9a12be /bin/bash
But the MySQL service does not start automatically, I have to manually run (from within the container):
service mysql start
How do I automatically start the MySQL service when I run the docker container?
Simple! Add at the end of dockerfile:
First, there is a problem in your
Dockerfile
:Docker images do not save running processes. Therefore, your
RUN
command executes only duringdocker build
phase and stops after the build is completed. Instead, you need to specify the command when the container is started using theCMD
orENTRYPOINT
commands like below:Secondly, the docker container needs a process (last command) to keep running, otherwise the container will exit/stop. Therefore, the normal
service mysql start
command cannot be used directly in the Dockerfile.Solution
There are three typical ways to keep the process running:
Using
service
command and append non-end command after that liketail -F
This is often preferred when you have a single service running as it makes the outputted log accessible to docker.
Or use foreground command to do this
This works only if there is a script like
mysqld_safe
.Or wrap your scripts into
start.sh
and put this in endThis is best if the command must perform a series of steps, again,
/start.sh
should stay running.Note
For the beginner using
supervisord
is not recommended. Honestly, it is overkill. It is much better to use single service / single command for the container.BTW: please check https://registry.hub.docker.com for existing mysql docker images for reference
In my case, I have a PHP web application being served by Apache2 within the docker container that connects to a MYSQL backend database. Larry Cai's solution worked with minor modifications. I created a
entrypoint.sh
file within which I am managing my services. I think creating anentrypoint.sh
when you have more than one command to execute when your container starts up is a cleaner way to bootstrap docker.