Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Start Services in Docker Container

I'm doing some initial tests with docker. At moment i have my images and I can put some containers running, with:

docker ps

I do docker attach container_id and start apache2 service.

Then from the main console I commit the container to the image.

After exiting the container, if I try to start the container or try to run one new container from the committed image, the service is always stopped.

How can create or restart one container with the services started, for example apache?

like image 990
Pedro Avatar asked Aug 04 '13 21:08

Pedro


People also ask

How do I start a service in a docker container?

Run Docker Container as a Service Docker team recommends to use cross-platform built-in restart policy for running container as a service. For this, configure your docker service to start on system boot and simply add parameter --restart unless-stopped to the docker run command that starts YouTrack.

Does docker start automatically?

Docker provides restart policies to control whether your containers start automatically when they exit, or when Docker restarts. Restart policies ensure that linked containers are started in the correct order. Docker recommends that you use restart policies, and avoid using process managers to start containers.

Does Docker compose auto restart?

Restart Policy in Docker Compose yml file. Docker Compose uses the same values provided by the Docker CLI restart command to define a restart strategy. Notice how we added the restart property to both services. In this case, the message-server will never restart automatically.


2 Answers

Try to add start script to entrypoint in dockerfile like this;

ENTRYPOINT service apache2 restart && bash
like image 55
Grzegorz Brzęczyszczykiewicz Avatar answered Sep 28 '22 03:09

Grzegorz Brzęczyszczykiewicz


EDIT: I've learned a lot about Docker since originally posting this answer. "Starting services automatically in Docker containers" is not a good usage pattern for Docker. Instead, use something like fleet, Kubernetes, or even Monit/SystemD/Upstart/Init.d/Cron to automatically start services that execute inside Docker containers.

ORIGINAL ANSWER: If you are starting the container with the command /bin/bash, then you can accomplish this in the manner outlined here: https://stackoverflow.com/a/19872810/2971199

So, if you are starting the container with docker run -i -t IMAGE /bin/bash and if you want to automatically start apache2 when the container is started, edit /etc/bash.bashrc in the container and add /usr/local/apache2/bin/apachectl -f /usr/local/apache2/conf/httpd.conf (or whatever your apache2 start command is) to a newline at the end of the file.

Save the changes to your image and restart it with docker run -i -t IMAGE /bin/bash and you will find apache2 running when you attach.

like image 38
damick Avatar answered Sep 28 '22 01:09

damick