How to run both Mysql and Apache from my Dockerfile?

Viewed 1117

I'm trying to create a Docker image for a project we have at our company, and I don't want to have to run mysql and apache manually after I create a container. Here's what my Dockerfile looks like at the moment:

FROM php:7.4-apache 

RUN apt-get update \
    && apt-get install -y default-mysql-server libzip-dev nano\
    && docker-php-ext-install zip mysqli pdo pdo_mysql \
    && docker-php-ext-enable mysqli

RUN /etc/init.d/mysql start \
    && sleep 5 \
    && mysql -u root -e "CREATE DATABASE eccube" \
    && mysqladmin -u root password 'secret'

COPY ./src_files /var/www/html

Problem is, when i start the container, the mysql process is not running, so I have to get into the container and run /etc/init.d/mysql start. Or, I tried to start the mysql process with a CMD call in my Dockerfile:

CMD /usr/sbin/mysqld -u mysql

But this means that now it's the Apache server that does not start, and I have to run it manually.

I have had too little sleep and too many cups of coffee, so the Docker documentation is looking like Chinese to me. Can someone explain how to run more than one background process correctly from a Dockerfile?

Thanks a lot!

1 Answers

Keep in mind that the RUN commands are executed when a container image is built, while CMD runs when a container is started - and you can only have one command. That is why you are only seeing either MySQL or Apache running.

Have you looked into Docker Compose? This would allow you to run your database in one container and your Apache server in another, and start both easily with docker-compose up.

If you do want to put everything in a single container, you could do that still though; you might consider a single Bash script to start both. You would add that Bash script to your Docker build process, and then setup CMD to run that script, instead of starting just MySQL or just Apache. The Docker documentation has some examples here for how to setup a single container with multiple services.

I personally think what you're trying to do would best be accomplished with Docker Compose, so that you are separating your concerns, but I don't know the details of your application.

Related