Declarative Jenkins Pipeline syntax that removes a previous Docker container and then starts a new one with the same name
Below is an example of a declarative Jenkins Pipeline syntax that removes a previous Docker container and then starts a new one with the same name:
COPY and USE THIS
```groovy
pipeline {
agent any
stages {
stage('Remove Previous Container') {
steps {
script {
try {
sh 'docker stop my_container || true'
sh 'docker rm my_container || true'
} catch (Exception e) {
echo "An error occurred: ${e.message}"
}
}
}
}
stage('Start New Container') {
steps {
script {
sh 'docker run -d --name my_container my_image:my_tag'
}
}
}
}
}
```
Here's what this pipeline does:
1. `pipeline { ... }`: This defines a declarative pipeline.
2. `agent any`: This specifies that the pipeline can run on any available agent (Jenkins worker node).
3. `stages { ... }`: This is where you define the different stages of your pipeline.
4. `stage('Remove Previous Container') { ... }`: This is the first stage, named "Remove Previous Container".
- `steps { ... }`: This is where you define the steps to be executed in this stage.
- `script { ... }`: This allows you to write arbitrary Groovy code, including shell commands.
- `try { ... } catch (Exception e) { ... }`: This is a try-catch block in Groovy. It attempts to execute the code inside the try block. If an exception occurs, it will be caught, and the code inside the catch block will be executed.
- `sh 'docker stop my_container || true'`: This is a shell command executed using the `sh` step. It attempts to stop a Docker container named `my_container`. The `|| true` part ensures that the command does not fail if the container is not currently running.
- `sh 'docker rm my_container || true'`: This command attempts to remove a Docker container named `my_container`. The `|| true` part ensures that the command does not fail if the container doesn't exist.
- `catch (Exception e) { ... }`: If an exception occurs during the attempt to stop or remove the container, this block will be executed. It captures the exception and provides a way to handle it.
- `echo "An error occurred: ${e.message}"`: This line will print a message indicating that an exception was caught, along with the error message.
5. `stage('Start New Container') { ... }`: This is the second stage, named "Start New Container".
- `steps { ... }`: This is where you define the steps to be executed in this stage.
- `script { ... }`: Again, this allows you to write arbitrary Groovy code.
- `sh 'docker run -d --name my_container my_image:my_tag'`: This command starts a new Docker container using the specified image, with the name and tag defined in the environment variables.
Please adapt this example to your specific use case and ensure that it fits within your Jenkins environment and Docker setup.
Comments
Post a Comment