dockerubuntu-20.04docker-run

How to automatically execute a command from a docker container on boot the container from the container's shell?


I have a container named test. I want to be able to start the container on Ubuntu boot which I think I can do with the always command.

Then I want to run one command when the container boots. For instance, I want to run ls so it shows me the list of files and directories within the container.

How do I run the ls command when the docker container boots? So, there are two things:

Docker container boots automatically on Ubuntu booting

As soon as the container boots, from within the container, one command will be executed.

I can manually do it using:

sudo docker run --rm -it test

Then when the test container begins, I can type ls in the terminal.

I want to do it automatically on boot, the actual command will be different, I am using ls for simplicity.


Solution

  • You can trigger a command to execute upon container start by adding this to the end of your Dockerfile:

    CMD ls
    

    If you need more than one command, the easiest thing to do is create an executable shell script and invoke that with the CMD. You can learn more about that from the Docker documentation here.