container-projects / Jenkinsfile
Jenkinsfile
Raw
pipeline {
    agent any
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }
    environment {
        DOCKERHUB_CREDENTIALS = credentials('dockerhub-creds')
        APP_NAME = "react-multi-stage-build-app"
        IMAGE_TAG = "${env.BUILD_ID}-${env.GIT_COMMIT}"
    }
    stages {
        stage('Build image') {
            steps {
                echo 'Building...'
                dir('react-multi-build-app') {
                    sh "docker build -t ${DOCKERHUB_CREDENTIALS_USR}/${APP_NAME}:${IMAGE_TAG} ."
                }
            }
        }
        stage('Login') {
            steps {
                echo 'Login in ...'
                sh 'echo $DOCKERHUB_CREDENTIALS_PSW | docker login -u $DOCKERHUB_CREDENTIALS_USR --password-stdin'
            }
        }
        stage('Push image') {
            steps {
                echo 'Pushing ...'
                sh "docker push ${DOCKERHUB_CREDENTIALS_USR}/${APP_NAME}:${IMAGE_TAG}"
            }
        }
        stage('Pull image') {
            steps {
                echo 'Pulling image'
                sh "docker pull ${DOCKERHUB_CREDENTIALS_USR}/${APP_NAME}:${IMAGE_TAG}"
            }
        }
        stage('Deploy Image') {
            steps {
                script {
                    echo 'Deploying ...'
                    //def installCmd = "sudo apt install docker.io"
                    //def addDockerUserCmd = "sudo usermod -aG docker ubuntu && newgrp docker"
                    def dockerCmd = "docker run -p 80:80 -d ${DOCKERHUB_CREDENTIALS_USR}/${APP_NAME}:${IMAGE_TAG}"
                    def ec2Instance = "ubuntu@3.235.164.163"
                    sshagent(['server-key']) {
                        //sh "ssh -o StrictHostKeyChecking=no ${ec2Instance} ${installCmd}"
                        //sh "ssh -o StrictHostKeyChecking=no ${ec2Instance} ${addDockerUserCmd}"
                        sh "ssh -o StrictHostKeyChecking=no ${ec2Instance} ${dockerCmd}"
                    }
                }
            }
        }
    }
}