Deployment of Reactapp using Docker and Jenkins

pipeline {
    agent {label 'Docker'}
    environment {
        CI = 'false'
    }
    stages {
        stage('main') {
            steps {
                script {
                    if (containerId.isEmpty == 'true') {
                        stage('pull') {
                            sh 'docker pull chittimallanikhil/staticpages_ui:latest'
                            sh 'docker run -itd -p 443:443 chittimallanikhil/staticpages_ui'
                            sh 'docker run -itd -p 80:80 chittimallanikhil/staticpages_ui'
                        }
                    }
                    else{
                        stage("pull & Deploy") {
                            sh 'docker stop container $(docker container ls -aq)'
                            sh 'docker rm container $(docker container ls -aq)'
                            sh 'docker pull chittimallanikhil/staticpages_ui:latest'
                            sh 'docker run -itd -p 443:443 chittimallanikhil/staticpages_ui'
                            sh "docker run -itd -p 80:80 chittimallanikhil/staticpages_ui"
                        }
                    }
                }
            }
        }
    }
}

Iam getting error as :
groovy.lang.MissingPropertyException: No such property: containerId for class: groovy.lang.Binding at groovy.lang.Binding.getVariable(Binding.java:63) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:271) at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)

My Query is, i need to stop a running container and pull the image from the docker hub and run it using Jenkins pipeline. but continuous deployment is not happening, after once its stop and remove the container again when we run build now - it is telling that no such container
For that purpose to overcome that, i am using if & else statement. can you help if there is any wrong in it??

containerId is never defined, so the code is saying containerId doesn’t exist.

Also I’m not sure the condition actually makes sense in this case.

if you add --rm to your docker runs, you don’t need to docker rm it
your docker stop container will stop everything. If you don’t want it to fail the build if it fails, you can do whatever || true in your sh statement, or use the sh(script: 'whatever', returnStatus: true)

You can also use when() instead of if in declarative, which will give you a bit better flow.

1 Like

Thanks for the suggestion it helps