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?
The following documentation from the Docker website shows how to implement an SSH service in a docker container. It should be easily adaptable for your service:
A variation on this question has also been asked here:
Might need to prune the existing container using docker prune ...
Import with required modifications:
Run the container for example with always restart option to make sure it will auto resume after host/daemon recycle:
Side note: In my opinion reasonable is to start only cron service leaving container as clean as possible then just modify crontab or cron.hourly, .daily etc... with corresponding checkup/monitoring scripts. Reason is You rely only on one daemon and in case of changes it is easier with ansible or puppet to redistribute cron scripts instead of track services that start at boot.
I add the following code to /root/.bashrc to run the code only once,
Please commit the container to the image before run this script, otherwise the 'docker_services' file will be created in the images and no service will be run.
Here is how I automatically start the MySQL service whenever the docker container runs.
On my case, I need to run not just MySQL but also PHP, Nginx and Memcached
I have the following lines in Dockerfile
Adding && bash would keep Nginx, MySQL, PHP and Memcached running within the container.
In your
Dockerfile
, add at the last lineIt works for me
And this is the result:
There's another way to do it that I've always found to be more readable.
Say that you want to start rabbitmq and mongodb when you run it then your
CMD
would look something like this:Since you can have only one
CMD
perDockerfile
the trick is to concatenate all instructions with&&
and then use\
for each command to start a new line.If you end up adding to many of those I suggest you put all your commands in a script file and start it like @larry-cai suggested: