pipeline { agent any stages { stage('Checkout') { steps { checkout scm } } stage('Build Image') { steps { echo 'Building image...' // --pull ensures base layer is fresh; tag includes BUILD_NUMBER to avoid cache clashes sh 'docker build --pull -t my-python-app:${BUILD_NUMBER} .' } } stage('Run Container') { steps { echo 'Running container...' // --rm cleans up; this will print "Hello, World!" to the console sh 'docker run --rm --name my-python-app-${BUILD_NUMBER} my-python-app:${BUILD_NUMBER}' } } stage('(Optional) Verify Output') { steps { script { // Re-run capturing output to assert expected behavior (example) def out = sh( script: 'docker run --rm my-python-app:${BUILD_NUMBER}', returnStdout: true ).trim() if (out != 'Hello, World!') { error "Unexpected output: '${out}'" } } } } } post { always { // Best-effort cleanup of any leftover container/image for this build tag sh ''' docker rm -f my-python-app-${BUILD_NUMBER} 2>/dev/null || true docker image rm my-python-app:${BUILD_NUMBER} 2>/dev/null || true ''' } } } ``