skip to Main Content

I ran the following command:

docker run python:3.8-alpine /bin/sh -c "timeout 1s sleep 5"

I expected it to terminate after 1 second, but it took 5 seconds to terminate instead.

If I enter the container and execute the command like below, it terminates correctly after 1 second:

docker run -it python:3.8-alpine /bin/sh
timeout 1s sleep 5

Why did the first command behave differently than expected?

4

Answers


  1. In Docker container this process /bin/sh -c "timeout 1s sleep 5" runs as PID 1.

    The timeout command uses the SIGTERM to stop a process.

    According to this link:

    A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. As a result, the process will not terminate on SIGINT or SIGTERM unless it is coded to do so.

    And according to this link:

    The only signals that can be sent to process ID 1, the init
    process, are those for which init has explicitly installed signal
    handlers. This is done to assure the system is not brought down
    accidentally.

    You must tell Docker to run the container with --init option (runs an init process):

    docker run --init python:3.8-alpine /bin/sh -c "timeout 1s sleep 5"
    
    Login or Signup to reply.
  2. you can also kill the PID 1 with trap and kill the process.
    Trap allows you to catch signals and execute code when they occur.

    docker run python:3.8-alpine /bin/sh -c "trap "exit" SIGINT SIGTERM && timeout 1s sleep 5"
    
    Login or Signup to reply.
  3. you can also do this:

    timeout -s KILL 1s docker run python:3.8-alpine /bin/sh -c "sleep 5"
    
    Login or Signup to reply.
  4. It’s not the correct question.
    when you run

    /bin/sh -c "timeout 1s sleep 5"
    

    you said to execute the sleep command and wait for 1 second to execute it. also when you use the -c option you said to sh execute this command as a parameter of sh. but without the -c option it would like to execute from a file and said no such file or directory to execute so you thought your timeout executed but it’s not true.

    Example:
    on your terminal type the following commands to catch it:

    1. #bash "echo hi"
    

    it said no such file or directory

    2. #bash -c "echo hi"
    

    it was executed correctly.

    I hope I was able to convey my meaning.

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