Search code examples
dockerdockerfilecontainers

Docker: Set timeout and Exit with Error Code


How can make a Docker container exit with an error code after a timeout?

I have a Dockerfile which uses the ubuntu image and copies the script file from my directory to image and finally exectues the script in a container.

FROM ubuntu
WORKDIR /usr/bin/
COPY ./example.py .
RUN chmod +x example.py
ENTRYPOINT ["python3", "example.py"]

Then I run the build command:

docker build -t demo .

run the container:

docker run -it --rm demo

I'm not sure how long does it take to successfully execute the example.py script but I want to exit the container after 1 hour. If the example.py script executed successfully within 1 hour then it's ok otherwise I want to exit with error code.


Solution

  • You can use the timeout command like this :

    ENTRYPOINT ["timeout", "3600", "python3", "example.py"]
    

    If python3 example.py takes more than 1 hour (3'600 seconds), an error will be returned (exit code 124).