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

The mysql service does not start automatically i have to run manually from within the container

service mysql start

Tell me the best way to start my server automatically when i use the container docker?

Best Answer


First, there is a problem in your Dockerfile .

RUN service mysql restart && /tmp/setup.sh

Docker images don't save processes running 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 like tail -F

    CMD service mysql start && tail -F /var/log/mysql/error.log
    

This is often preferred when you have a single service running because 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 end

    CMD /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. I mean it's totally overkill It is much better to use one command for the container

BTW: please check https://registry.hub.docker.com for existing mysql docker images for reference