How to launch an AWS EC2 instance with Docker Engine installed

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 a virtual machine instance.

Learn how to quickly install Docker Engine and Docker Compose on AWS EC2, using any Ubuntu AMI and bootstrapping the install script.

According to Snap Store, the top 14 linux distros where Docker Engine is installed are all Ubuntu (or Ubuntu-based).

docker-snap

EC2 Instance with launch script (user data)

In this method I will use AWS EC2 user data feature, which allows a specific script to run during instance launch (bootstrap). I will install the docker engine from the snap store, followed by Linux post-installation steps to be able to run docker commands such as docker run without sudo.

  1. Login to AWS EC2 page and make sure you are in the correct region
  2. Click Launch instance.
  3. Choose Ubuntu from the quick start page. Current default version is Ubuntu 22.04 LTS.
  4. Choose the instance size for your instance. t2.micro size is Free tier eligible, and is sufficient to run simple workloads in Docker.
  5. Create key pair and fill any other required configuration settings.
  6. Under Advanced details section, paste the install script in the User data box:
aws-ec2-user-data-bootstrap
#!/bin/bash
sudo snap install docker
sudo addgroup --system docker
sudo adduser ubuntu docker
newgrp docker
sudo snap disable docker
sudo snap enable docker
  1. Review and launch the instance.

  2. Once your instance is up and running, wait a few minutes for the instance to initialize, then SSH to it using an SSH client like Putty .

  3. Verify Docker is running using any of the following commands:

docker -v
docker ps
docker compose version 
docker info
docker-snap-running

Congratulations, you have built an Ubuntu VM with Docker Engine and Docker Compose running on first boot!

Further reads