How to start apache2 automatically in a ubuntu docker container?

Posted on Jan 22, 2022

Question

I am trying to create a Dockerfile that will start apache automatically. Nothing has worked. But If I log into the container and run service apache2 start it works. Why can I not run that command from my Dockerfile?

FROM ubuntu

File Author / Maintainer

MAINTAINER rmuktader

Update the repository sources list

RUN apt-get update

Install and run apache

RUN apt-get install -y apache2 && apt-get clean

#ENTRYPOINT ["/usr/sbin/apache2", “-k”, “start”]

#ENV APACHE_RUN_USER www-data #ENV APACHE_RUN_GROUP www-data #ENV APACHE_LOG_DIR /var/log/apache2

EXPOSE 80 CMD service apache2 start

Answer

The issue is here: CMD service apache2 start When you execute this command process apache2 will be detached from the shell. But Docker works only while main process is alive.

The solution is to run Apache in the foreground. Dockerfile must look like this: (only last line changed).

FROM ubuntu

File Author / Maintainer

MAINTAINER rmuktader

Update the repository sources list

RUN apt-get update

Install and run apache

RUN apt-get install -y apache2 && apt-get clean

#ENTRYPOINT ["/usr/sbin/apache2", “-k”, “start”]

#ENV APACHE_RUN_USER www-data #ENV APACHE_RUN_GROUP www-data #ENV APACHE_LOG_DIR /var/log/apache2

EXPOSE 80 CMD apachectl -D FOREGROUND