Amazon EC2 provides virtual machines when a workload needs operating-system control, custom software, predictable long-running compute, or migration compatibility.
An instance combines an AMI, instance type, subnet, security groups, storage, metadata settings, and an IAM role. Those choices affect performance, availability, security, and price.
Production EC2 design should assume instances are replaceable: bootstrap from code, keep state outside the instance where practical, and recover through an Auto Scaling group or tested image.
Select a maintained AMI and size the instance for CPU, memory, network, architecture, and accelerator needs. Measure the application before moving to a larger family.
Place application instances in the subnet that matches their exposure. Security groups should permit only required traffic, and Systems Manager Session Manager is usually safer than opening SSH or RDP to the internet.
EBS volumes persist independently according to their delete-on-termination setting. User data can bootstrap packages and agents, but complex configuration is easier to version and test with images or configuration management.
Use load balancer health checks, Auto Scaling, CloudWatch metrics, and centralized logs. Replace an unhealthy instance from a known configuration instead of repairing unique server state by hand.
Launching an instance creates a virtual server from an AMI in one Availability Zone. Pending, running, stopping, stopped, shutting-down, and terminated states affect billing and attached resources differently. Stopping an EBS-backed instance preserves its EBS volumes but does not make every related resource free; public IPv4 addresses, unattached storage, snapshots, and other components can continue to incur charges.
A stop and start can move the virtual machine to different host hardware and usually changes an automatically assigned public IPv4 address. A reboot keeps the instance on the same underlying placement when possible and does not have the same lifecycle boundary. Applications must not treat ephemeral host details as durable identity.
Termination is destructive for instance-store data and for EBS volumes configured to delete on termination. Protect critical instances from accidental termination only as a secondary control; the primary recovery strategy is external state, tested backups, and reproducible replacement from a maintained image or launch template.
An AMI defines the root volume image, architecture, virtualization details, and launch permissions. Use an AWS, vendor, or internally produced image with a known owner and patch process. Pin an approved image identifier through a controlled parameter or image pipeline rather than selecting an unreviewed latest image during every production launch.
User data is suitable for bounded bootstrap work such as registering the host, retrieving configuration through its role, and starting the application. On common Linux images, cloud-init records output that should be collected when bootstrap fails. User data can run with high local privilege, so it must not contain long-lived credentials or accept untrusted input.
A golden-image pipeline reduces startup work but creates an image supply chain that needs package updates, vulnerability scanning, signing or provenance controls, and retirement. Keep application release identity separate from the base-image release, and exercise rollback with both old application and old image compatibility in mind.
EBS provides network-attached block volumes within one Availability Zone. Select volume type, size, throughput, and IOPS from measured workload behavior, and monitor queueing and latency rather than only free filesystem space. Expanding a volume may also require growing its partition and filesystem inside the operating system.
Snapshots are incremental point-in-time backups stored by the service, but application-consistent recovery may require quiescing writes or coordinating database-native backup behavior. Encrypt new volumes and snapshots according to the key policy and recovery requirements. Copying or sharing an encrypted snapshot also involves KMS permissions.
Instance store is physically attached temporary block storage on supported instance types. It can be valuable for caches, scratch data, and replicated workloads, but data is lost under lifecycle events documented for the instance. Never keep the only copy of business data there. Test low-disk behavior and restore a snapshot before trusting the backup design.
An instance network interface receives private addresses and security groups inside a subnet. Route tables and gateways determine reachability; a public address alone does not create a complete path. Put internet-facing load balancers in public subnets and application instances in private subnets when the workload does not require direct inbound internet access.
Security groups should reference other security groups for tier-to-tier access when that expresses the relationship more safely than changing address lists. Keep administrative access behind Session Manager, a controlled bastion, VPN, or another approved path. Require IMDSv2 and restrict metadata access from containers or proxies that do not need it.
A load balancer health check should indicate whether the instance can serve useful traffic, while the Auto Scaling health policy determines when it is replaced. Separate liveness from deep dependency checks so a temporary shared-database problem does not cause every healthy process to be replaced simultaneously.
A launch template records the image, instance type choices, role, network settings, storage, and bootstrap used by an Auto Scaling group. Version it and promote a tested version deliberately. Mixed instance types can improve availability and price, but only when the application and performance target tolerate the selected families and architectures.
Set minimum, desired, and maximum capacity from availability needs and safe cost limits. Target tracking responds to a metric, scheduled scaling handles known cycles, and step policies can react to thresholds. Scaling is not instantaneous: image pull, bootstrap, registration, caches, and warm-up affect when new capacity becomes useful.
Test scale-out, scale-in, an unhealthy instance, an Availability Zone capacity shortage, and a deployment while traffic is active. Protect long work with lifecycle hooks or queue visibility rules before scale-in. Monitor rejected work and latency because average CPU can look healthy while one downstream limit is saturated.
On-Demand capacity is a flexible baseline, Savings Plans or Reserved Instances can reduce eligible steady usage, and Spot Instances use spare capacity that can be interrupted. Choose from workload tolerance and measured baseline rather than headline discount. Capacity Reservations solve placement availability, which is a different concern from a billing commitment.
Patch the operating system and agents through an image replacement or controlled patch workflow. Centralize logs, collect application and system metrics, monitor EC2 status checks, and route alarms to an owner. Use Systems Manager inventory and automation only after the instance role and network path are intentionally scoped.
When an instance fails, preserve enough evidence to distinguish application, operating-system, storage, network, and platform status problems, then replace it through the normal mechanism. Avoid manual repair that creates an undocumented production-only server. A fleet is operable when any member can disappear without losing unique configuration or data.
This launch pattern is safer than key-pair-only access because the instance can be managed through Systems Manager and can assume an IAM role for resource access.
aws ec2 run-instances \
--image-id ami-1234567890abcdef0 \
--instance-type t3.micro \
--iam-instance-profile Name=EC2AppRole \
--subnet-id subnet-123456 \
--security-group-ids sg-123456 \
--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=orders-api-dev}]"
One instance in an Auto Scaling group fails its application health check during a release.
Constraints: User data is repeatable, state lives outside the instance, and the load balancer drains connections before termination.
Decision: Mark the instance unhealthy and let the group replace it from the approved AMI instead of repairing it interactively.
Verification: Desired capacity returns, the new instance passes target health, and no session or uploaded file was lost.
Failure test: Terminate a second instance during replacement and confirm the minimum healthy capacity is preserved.
Expected evidence: Desired capacity returns, the new instance passes target health, and no session or uploaded file was lost.
Explore 500+ free tutorials across 20+ languages and frameworks.