skip to Main Content

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:

  1. It runs in interactive mode (as one would expect), while I need something that can run on a server, without human supervision.
  2. I need to perform a docker cp commands before executing the command I need to run.

Basically, what I have is:

  • docker create creates the container.
  • docker cp moves over the files I need.
  • docker start starts the container, but since it has no default command to run, it exits immediately.
  • docker exec refuses to run my command, because the container is stopped. No amount of docker start can 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 createstartattach) would be already existing, but I can’t seem to find anything neither in the documentation nor in other forum answers.

2

Answers


  1. Chosen as BEST ANSWER

    @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.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search