mjbeyeler
mjbeyeler

Reputation: 483

Is there an easy way to automatically run a script whenever I (re)start a container?

I have built a Docker image, copied a script into the image, and automatically execute it when I run the image, thanks to this Dockerfile command:

ENTRYPOINT ["/path/to/script/my_script.sh"]

(I had to give it chmod rights in a RUN command to actually make it run)

Now, I'm quite new to Docker, so I'm not sure if what I want to do is even good practice:

My basic idea is that I would rather not always have to create a new container whenever I want to run this script, but to instead find a way to re-execute this script whenever I (re)start the same container.

So, instead of having to type docker run my_image, accomplishing the same via docker (re)start container_from_image.

Is there an easy way to do this, and does it even make sense from a resource parsimony perspective?

Upvotes: 1

Views: 2097

Answers (2)

MyTwoCents
MyTwoCents

Reputation: 7624

For chmod issue you can do something like this

COPY . /path/to/script/my_script.sh
RUN chmod 777 -R /path/to/script/my_script.sh

For rerun script issue

The ENTRYPOINT specifies a command that will always be executed when the container starts.

It can be either

docker run container_from_image

or

docker start container_from_image

So whenever your container start your ENTRYPOINT command will be executed.

You can refer this for more detail

Upvotes: 1

David Maze
David Maze

Reputation: 158995

docker run is fairly cheap, and the typical Docker model is generally that you always start from a "clean slate" and set things up from there. A Docker container doesn't have the same set of pre-start/post-start/... hooks that, for instance, a systemd job does; there is only the ENTRYPOINT/CMD mechanism. The way you have things now is normal.

Also remember that you need to delete and recreate containers for a variety of routine changes, with the most important long-term being that you have to delete a container to change the underlying image (because the installed software or the base Linux distribution has a critical bug you need a fix for). I feel like a workflow built around docker build/run/stop/rm is the "most Dockery" and fits well with the immutable-infrastructure pattern. Repeated docker stop/start as a workflow feels like you're trying to keep this specific container alive, and in most cases that shouldn't matter.

From a technical point of view you can think of the container environment and its filesystem, and the main process inside the container. docker run is actually docker create plus docker start. I've never noticed the "create" half of this taking substantial time, but if you're doing something like starting a JVM or loading a large dataset on startup, the "start" half will be slow whether or not it's coupled with creating a new container.

Upvotes: 1

Related Questions