In some common situation like setting up testing or staging environment with ec2 instances, we need docker and docker compose installed to them. Although we can install them manually when they are created, although it will not make sense in this DevOps and automation arena unless having a very specific case.
So here is the basic example where we have aws cloudformation template which will create the Ec2 Linux instance & install the docker, docker compose in user-data script. The docker installation can be referred here in detail.
DockerInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ServerAMI
KeyName: !Ref ServerKey
InstanceType: !Ref ServerType
SecurityGroupIds:
- !Ref DockerServerSecurityGroup
SubnetId: !Ref ServerSubnet
Monitoring: 'true'
InstanceInitiatedShutdownBehavior: 'stop'
DisableApiTermination: 'true'
IamInstanceProfile:
!Ref InstanceProfile
Tags:
- Key: Name
Value: ‘docker-server'
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
sudo yum -y update
sudo yum install -y wget
sudo yum install -y docker
sudo service docker start
sudo usermod -a -G docker ec2-user
sudo curl -L https://github.com/docker/compose/releases/download/1.20.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
Assumptions:
When you execute this template, it will create an ec2 Linux with Docker & Docker compose installed on it.
Optionally, you can add any other bash commands in UserData script which you want to execute on the boot up of an instance.