How to launch an AWS EC2 instance with Docker Engine installed
- June 19, 2022
- Posted by: ElastiCourse
- Category: How-To Docker
AWS EC2 is a great service to run virtual machines in the cloud. EC2 offers hundreds of images of operating systems and pre-packaged applications to choose from when launching an instance (aka virtual machine).
To start using Docker Engine and Docker Compose to create containers and stacks on AWS EC2, we recommend building on Ubuntu 20.04 (Focal) AMI which is usually displayed in Quick Start page of the EC2 launcher.
Side Note: did you know that 8 out of 10 users are using Docker Engine on Ubuntu OS? With Ubuntu 20.04 being top used distro to host Docker Engine according to Snap Store.
EC2 Instance with launch script (user data)
In this method we will use AWS EC2 user data feature, which allows a specific script to run during instance launch (one time run), the user data or the launch script will contain the interpreter used to run the command, in ubuntu and debian-based systems it’s called bash, and within bash we will install the docker engine from the snap store, then we will follow Docker Documentation post-install instructions to be able to run docker commands including docker run without having to use root level sudo command.
- Head into AWS EC2 page, make sure you are on the correct region that you want to deploy your virtual machine instance within. The following solution was built in N. Virginia (US-EAST-1) region, but instructions are the same for all regions.
- Click “Launch instance”
- Choose Ubuntu Server 20.04 LTS from the quick start page.
- Choose the instance size for your instance, t2.micro size is Free tier eligible, and is sufficient to run simple workloads on Docker.
- In the instance details step, go down to the advanced details section, the User data section can be used to paste the install script below:
#!/bin/bash sudo snap install docker sudo addgroup --system docker sudo adduser ubuntu docker newgrp docker sudo snap disable docker sudo snap enable docker
6. Review and Launch the instance, you will be asked to create a key pair, or choose an existing one, to be able to access and login the virtual machine instance, this is also referred to as key-based user authentication, compared to the traditional, less-secure, password-based user authentication.
7. Once your instance is up and running, wait a few minutes for the instance to initialize, then you can SSH to it using a program like Putty.
8. Verify Docker is running using any of the following commands
Sample output: Docker version 19.03.13, build cd8016b6bc
Congratulations, you have built an Ubuntu system with Docker Engine and Docker Compose running on first boot!