I have a docker container based on an image that, by default, does not run any command when started. I need to execute a command in that container.
Running docker run -it [container tag] runs, but there are two problems:
- It runs in interactive mode (as one would expect), while I need something that can run on a server, without human supervision.
- I need to perform a
docker cpcommands before executing the command I need to run.
Basically, what I have is:
docker createcreates the container.docker cpmoves over the files I need.docker startstarts the container, but since it has no default command to run, it exits immediately.docker execrefuses to run my command, because the container is stopped. No amount ofdocker startcan fix this.
I cannot edit the image Dockerfile, so unfortunately, adding a while true; done (suggested here) as default command to run isn't possible.
I assumed a command that would chain start and exec back-to-back (and ensure the container doesn't close before the command is run, similar to how run is create-start-attach) would be already existing, but I can't seem to find anything neither in the documentation nor in other forum answers.
CodePudding user response:
You could just mount your dir where your file you need to copy is directly into the container then run the command you need. In this example I am just running an ls, but I could also run the script its self
sample file
#!/bin/bash
echo "running this on $(hostname)"
date
echo "ending....."
$ docker run -v $(pwd)/scripts:/myscripts ubuntu ls -lrt ./myscripts/stack.sh
-rwxrwxrwx 1 root root 70 Jan 24 05:43 ./myscripts/stack.sh
$ docker run -v $(pwd)/scripts:/myscripts ubuntu ./myscripts/stack.sh
running this on 63b65348373a
Tue Jan 24 05:44:22 UTC 2023
ending.....
In either case I am essentially mounting my script into the container image then running a command using the file I have mounted in.
CodePudding user response:
@Hans Kilian's comment made me remember that the argument passed to docker run (after the image) is a replacement for the entry point. Therefore, if I have an image without an entry point by default, I can simply run:
docker run -d [image] sleep infinity
...and it will launch the container with a process that won't exit.
Afterwards, I am free to run as many docker cp and docker exec as I want.
