Coolbreeze
Coolbreeze

Reputation: 947

How to wait for a docker container to exit/timeout when it reaches the completion

I have a JenkinsFile where i have a postgresql container running. But i need to write a logic which will wait for the docker container to timout/exit.

Currently, i have something like this

psql_container=sh(script: "docker inspect psqlcont --format='{{.State.ExitCode}}'", returnStdout: true).trim()

sh "sleep 1000"

if (psql_container != '0'){
                    error "psql failed ..."
                }else{
                 echo "psql starts"
                

Instead of sleep, i need to write a condition where the container will quit/timeout in 1000 seconds.

Upvotes: 1

Views: 2126

Answers (2)

David Maze
David Maze

Reputation: 158898

The docker wait command will wait (indefinitely) for a container to complete. The Jenkins pipeline timeout step will run some block but abort after a deadline. You can combine these to wait for a container to finish, or kill it if it takes too long:

try {
  timeout(1000, unit: SECONDS) {
    sh "docker wait psqlcont"
  }
} catch(e) {
  sh "docker stop psqlcont"
  sh "docker wait psqlcont" // <= 10s, container is guaranteed to be stopped
}
sh "docker rm psqlcont"

Upvotes: 3

Shaqil Ismail
Shaqil Ismail

Reputation: 1961

You can use the timeout command, instead of sleep,

timeout [OPTIONS] DURATION COMMAND [ARG]… Copy The DURATION can be a positive integer or a floating-point number, followed by an optional unit suffix:

s - seconds (default) m - minutes h - hours d - days

You can send a command when the timeout time has been reached also,

For example, to send SIGKILL to the ping command after one minute, you would use:

sudo timeout -s SIGKILL ping 8.8.8.8

Upvotes: 0

Related Questions