Hands-On: Launch a Web Server
Start an instance that installs and runs a web server on first boot.
1 min read
User data is a script that runs automatically the first time an instance boots. It's the simplest way to
set up a server without logging in. Save this as setup.sh:
Terminal
#!/bin/bash
dnf install -y nginx
echo "<h1>Hello from EC2</h1>" > /usr/share/nginx/html/index.html
systemctl enable --now nginxThen launch it. This uses your account's default VPC. The resolve:ssm: image ID always picks the
latest Amazon Linux 2023 AMI, so you don't have to look up IDs per Region.
Try it
Terminal
# 1. A security group that allows HTTP from anywhere
SG_ID=$(aws ec2 create-security-group \
--group-name web-demo --description "Allow HTTP" \
--query GroupId --output text)
aws ec2 authorize-security-group-ingress \
--group-id $SG_ID --protocol tcp --port 80 --cidr 0.0.0.0/0
# 2. Launch the instance with our setup script
aws ec2 run-instances \
--image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
--instance-type t3.micro \
--security-group-ids $SG_ID \
--user-data file://setup.sh \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-demo}]' \
--query 'Instances[0].InstanceId' --output text
# 3. After a minute, get its public IP and open it in a browser
aws ec2 describe-instances --filters Name=tag:Name,Values=web-demo \
--query 'Reservations[].Instances[].PublicIpAddress' --output textStop vs. terminate
- Stop: the instance shuts down. You stop paying for compute but still pay for its EBS disk. Start it again later.
- Terminate: the instance is deleted for good. By default, its root disk is deleted too.
Watch out
Don't forget to clean up when you're done experimenting:
aws ec2 terminate-instances --instance-ids i-0a1b2c3d4e5f67890
Key takeaways
- User data scripts configure an instance automatically on first boot.
- resolve:ssm: parameters always fetch the latest official AMI ID.
- Stopped instances still cost money for their disks. Terminate what you don't need.
Check your understanding
Pick an answer to see the explanation.
1. You stop an instance for a month. What are you still paying for?