Deploy Docker Images to Amazon EC2 with Jenkins

Jenkins Sep 08, 2020

Configure SSH Connection

  • Generate SSH Key within the Jenkins server:
$ ssh-keygen -t rsa

Output
Generating public/private rsa key pair.
Enter file in which to save the key (/home/demo/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/demo/.ssh/id_rsa.
Your public key has been saved in /home/demo/.ssh/id_rsa.pub.
The key fingerprint is:
4a:dd:0a:c6:35:4e:3f:ed:27:38:8c:74:44:4d:93:67 demo@a
The key's randomart image is:
+--[ RSA 2048]----+
|          .oo.   |
|         .  o.E  |
|        + .  o   |
|     . = = .     |
|      = S = .    |
|     o + = +     |
|      . o + o .  |
|           . o   |
|                 |
+-----------------+
  • Copy your public key:  cat id_rsa.pub
  • Connect to your Amazon EC2 instance and append the content of your public key to end of file in a new line: nano ~/.ssh/authorized_keys
  • Now you can verify that Jenkins can connect to Amazon instance: ssh USER@REMOTE_ADDR

Prepare a build script

Commit the build script to your code repository:

echo "Starting to deploy docker image.."
DOCKER_IMAGE=turkogluc/spring-jenkins-demo
docker pull $DOCKER_IMAGE
docker ps -q --filter ancestor=$DOCKER_IMAGE | xargs -r docker stop
docker run -d -p 8080:8080 $DOCKER_IMAGE
deploy.sh

So it pulls the latest image from docker artifactory, stops the container if it is already working and runs it with latest version.

Add deploy stage to Jenkins

pipeline {
    agent any

    triggers{
        bitbucketPush()
    }
    
    stages {
		stage ("build") {
        	steps {
            	// build and publish docker image
            }
        }
    }

    stage ('Deploy') {
        steps {
            sh 'scp deploy.sh ${REMOTE_USER}@${REMOTE_HOST}:~/'
            sh 'ssh ${REMOTE_USER}@${REMOTE_HOST} "chmod +x deploy.sh"'
            sh 'ssh ${REMOTE_USER}@${REMOTE_HOST} ./deploy.ssh'
        }
    }
}

If you would like to have Continues Delivery pipeline separately, you can add docker artifactory trigger with CloudBees Docker Hub/Registry Notification from Manage Jenkins -> Manage Plugins -> Available.

You can add webhooks to docker hub as follows:

Docker Hub Webhooks

and set the build trigger:

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.