How to automatically start a service when running a docker container?
Solution 1:
First, there is a problem in your Dockerfile
:
RUN service mysql restart && /tmp/setup.sh
Docker images do not save running processes. Therefore, your RUN
command executes only during docker build
phase and stops after the build is completed. Instead, you need to specify the command when the container is started using the CMD
or ENTRYPOINT
commands like below:
CMD mysql start
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
CMD service mysql start && tail -F /var/log/mysql/error.log
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
CMD /usr/bin/mysqld_safe
This works only if there is a script like mysqld_safe
.
-
Or wrap your scripts into
start.sh
and put this in endCMD /start.sh
This 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
Solution 2:
In your Dockerfile
, add at the last line
ENTRYPOINT service ssh restart && bash
It works for me
And this is the result:
root@ubuntu:/home/vagrant/docker/add# docker run -i -t ubuntu
* Restarting OpenBSD Secure Shell server sshd [ OK ]
root@dccc354e422e:~# service ssh status
* sshd is running